Rewrite code styling of browser examples

This commit is contained in:
jos 2019-08-29 15:45:32 +02:00
parent 004d1100cd
commit 6bfede956b
23 changed files with 394 additions and 425 deletions

View File

@ -96,12 +96,12 @@ with npm (recommended):
<script>
// create the editor
var container = document.getElementById("jsoneditor")
var options = {}
var editor = new JSONEditor(container, options)
const container = document.getElementById("jsoneditor")
const options = {}
const editor = new JSONEditor(container, options)
// set json
var json = {
const initialJson = {
"Array": [1, 2, 3],
"Boolean": true,
"Null": null,
@ -109,10 +109,10 @@ with npm (recommended):
"Object": {"a": "b", "c": "d"},
"String": "Hello World"
}
editor.set(json)
editor.set(initialJson)
// get json
var json = editor.get()
const updatedJson = editor.get()
</script>
</body>
</html>

View File

@ -22,13 +22,13 @@
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {};
var editor = new JSONEditor(container, options);
const container = document.getElementById('jsoneditor')
const options = {}
const editor = new JSONEditor(container, options)
// set json
document.getElementById('setJSON').onclick = function () {
var json = {
const json = {
'array': [1, 2, 3],
'boolean': true,
'color': '#82b92c',
@ -36,15 +36,15 @@
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
editor.set(json);
};
}
editor.set(json)
}
// get json
document.getElementById('getJSON').onclick = function () {
var json = editor.get();
alert(JSON.stringify(json, null, 2));
};
const json = editor.get()
alert(JSON.stringify(json, null, 2))
}
</script>
</body>
</html>

View File

@ -23,22 +23,22 @@
<div id="jsoneditor"></div>
<script>
var container = document.getElementById('jsoneditor');
const container = document.getElementById('jsoneditor')
var options = {
const options = {
mode: 'view'
};
}
var json = {
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
}
var editor = new JSONEditor(container, options, json);
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -38,29 +38,29 @@
<div id="jsoneditor"></div>
<script>
var container = document.getElementById('jsoneditor');
const container = document.getElementById('jsoneditor')
var options = {
const options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onModeChange: function (newMode, oldMode) {
console.log('Mode switched from', oldMode, 'to', newMode);
console.log('Mode switched from', oldMode, 'to', newMode)
}
};
}
var json = {
const json = {
"array": [1, 2, 3],
"boolean": true,
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World"
};
}
var editor = new JSONEditor(container, options, json);
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -38,36 +38,36 @@
<script>
// create the editor
var editor = new JSONEditor(document.getElementById('jsoneditor'));
const editor = new JSONEditor(document.getElementById('jsoneditor'))
// Load a JSON document
FileReaderJS.setupInput(document.getElementById('loadDocument'), {
readAsDefault: 'Text',
on: {
load: function (event, file) {
editor.setText(event.target.result);
editor.setText(event.target.result)
}
}
});
})
// Save a JSON document
document.getElementById('saveDocument').onclick = function () {
// Save Dialog
fname = window.prompt("Save as...");
let fname = window.prompt("Save as...")
// Check json extension in file name
if(fname.indexOf(".")==-1){
fname = fname + ".json";
}else{
if(fname.split('.').pop().toLowerCase() == "json"){
if (fname.indexOf(".") === -1) {
fname = fname + ".json"
} else {
if (fname.split('.').pop().toLowerCase() === "json") {
// Nothing to do
}else{
fname = fname.split('.')[0] + ".json";
} else {
fname = fname.split('.')[0] + ".json"
}
}
var blob = new Blob([editor.getText()], {type: 'application/json;charset=utf-8'});
saveAs(blob, fname);
};
const blob = new Blob([editor.getText()], {type: 'application/json;charset=utf-8'})
saveAs(blob, fname)
}
</script>
</body>
</html>

View File

@ -25,9 +25,9 @@
<div id="jsoneditor"></div>
<script>
var container = document.getElementById('jsoneditor');
const container = document.getElementById('jsoneditor')
var options = {
const options = {
onEditable: function (node) {
// node is an object like:
// {
@ -37,27 +37,27 @@
// }
switch (node.field) {
case '_id':
return false;
return false
case 'name':
return {
field: false,
value: true
};
}
default:
return true;
return true
}
}
};
}
var json = {
const json = {
_id: 123456,
name: 'John',
age: 32
};
}
var editor = new JSONEditor(container, options, json);
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -22,30 +22,30 @@
</head>
<body>
<p>
This example demonstrates how to customize the look of JSONEditor,
the editor below has a dark theme. Note that the example isn't worked
out for the mode <code>code</code>. To do that, you can load and configure
a custom theme for the Ace editor.
</p>
<p>
This example demonstrates how to customize the look of JSONEditor,
the editor below has a dark theme. Note that the example isn't worked
out for the mode <code>code</code>. To do that, you can load and configure
a custom theme for the Ace editor.
</p>
<div id="jsoneditor"></div>
<div id="jsoneditor"></div>
<script>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
const container = document.getElementById('jsoneditor')
const options = {
modes: ['text', 'tree']
};
var json = {
}
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
</script>
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -34,7 +34,7 @@
<div id="jsoneditor"></div>
<script>
var schema = {
const schema = {
"title": "Employee",
"description": "Object containing employee details",
"type": "object",
@ -74,9 +74,9 @@
}
},
"required": ["firstName", "lastName"]
};
}
var job = {
const job = {
"title": "Job description",
"type": "object",
"required": ["address"],
@ -106,9 +106,9 @@
"examples": [100, 110, 120]
}
}
};
}
var json = {
const json = {
firstName: 'John',
lastName: 'Doe',
gender: null,
@ -119,18 +119,18 @@
role: 'developer',
salary: 100
}
};
}
var options = {
const options = {
schema: schema,
schemaRefs: {"job": job},
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview']
};
}
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -52,21 +52,21 @@
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
const container = document.getElementById('jsoneditor')
const options = {
modes: ['text', 'code', 'tree', 'form', 'view'],
mode: 'code',
ace: ace
};
var json = {
}
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -38,9 +38,9 @@
<div id="jsoneditor"></div>
<script>
var container = document.getElementById('jsoneditor');
const container = document.getElementById('jsoneditor')
var options = {
const options = {
mode: 'text',
modes: ['text', 'code'],
onEditable: function (node) {
@ -51,23 +51,23 @@
}
},
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onModeChange: function (newMode, oldMode) {
console.log('Mode switched from', oldMode, 'to', newMode);
console.log('Mode switched from', oldMode, 'to', newMode)
}
};
}
var json = {
const json = {
"array": [1, 2, 3],
"boolean": true,
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World"
};
}
var editor = new JSONEditor(container, options, json);
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -27,46 +27,45 @@
<div id="jsoneditor"></div>
<script>
var json = [
const json = [
{
firstName: 'John',
lastName: 'Doe',
age: 28
}
];
]
var options = {
templates: [
{
text: 'Person',
title: 'Insert a Person Node',
className: 'jsoneditor-type-object',
field: 'PersonTemplate',
value: {
'firstName': 'John',
'lastName': 'Do',
'age': 28
}
},
{
text: 'Address',
title: 'Insert a Address Node',
field: 'AddressTemplate',
value: {
'street': '',
'city': '',
'state': '',
'ZIP code': ''
}
}
]
};
const options = {
templates: [
{
text: 'Person',
title: 'Insert a Person Node',
className: 'jsoneditor-type-object',
field: 'PersonTemplate',
value: {
'firstName': 'John',
'lastName': 'Do',
'age': 28
}
},
{
text: 'Address',
title: 'Insert a Address Node',
field: 'AddressTemplate',
value: {
'street': '',
'city': '',
'state': '',
'ZIP code': ''
}
}
]
}
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
editor.expandAll();
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
</script>
</body>
</html>

View File

@ -6,7 +6,6 @@
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<style type="text/css">
#jsoneditor {
width: 500px;
@ -22,30 +21,30 @@
</head>
<body>
<p>
This example demonstrates how to autocomplete works, options available are: 'apple','cranberry','raspberry','pie', 'mango', 'mandarine', 'melon', 'appleton'.
This example demonstrates how to autocomplete works, options available are: 'apple','cranberry','raspberry','pie', 'mango', 'mandarine', 'melon', 'appleton'.
</p>
<div id="jsoneditor"></div>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
const container = document.getElementById('jsoneditor')
const options = {
autocomplete: {
getOptions: function () {
return ['apple', 'cranberry', 'raspberry', 'pie', 'mango', 'mandarine', 'melon', 'appleton'];
}
}
};
var json = {
}
const json = {
'array': [{'field1':'v1', 'field2':'v2'}, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -7,7 +7,6 @@
<script src="../dist/jsoneditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<style type="text/css">
#jsoneditor {
width: 500px;
@ -30,39 +29,39 @@
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
const container = document.getElementById('jsoneditor')
const options = {
autocomplete: {
applyTo:['value'],
filter: 'contain',
trigger: 'focus',
getOptions: function (text, path, input, editor) {
return new Promise(function (resolve, reject) {
var options = extractUniqueWords(editor.get());
if (options.length > 0) resolve(options); else reject();
});
const options = extractUniqueWords(editor.get())
if (options.length > 0) resolve(options) else reject()
})
}
}
};
}
// helper function to extract all unique words in the keys and values of a JSON object
function extractUniqueWords (json) {
return _.uniq(_.flatMapDeep(json, function (value, key) {
return _.isObject(value)
? [key]
: [key, String(value)]
? [key]
: [key, String(value)]
}))
}
var json = {
const json = {
'array': [{'field1':'v1', 'field2':'v2'}, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -31,74 +31,78 @@
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var activationChar = '*';
var options = {
const container = document.getElementById('jsoneditor')
const activationChar = '*'
const options = {
autocomplete: {
confirmKeys: [39, 35, 9, 190], // Confirm Autocomplete Keys: [right, end, tab, '.'] // By default are only [right, end, tab]
caseSensitive: false,
getOptions: function (text, path, input, editor) {
if (!text.startsWith(activationChar) || input !== 'value') return [];
var data = {};
var startFrom = 0;
var lastPoint = text.lastIndexOf('.');
var jsonObj = editor.get();
if (!text.startsWith(activationChar) || input !== 'value') return []
let data = {}
let startFrom = 0
const lastPoint = text.lastIndexOf('.')
const jsonObj = editor.get()
if ((lastPoint > 0) && (text.length > 1)) {
data = jsonpath.query(jsonObj, '$.' + text.substring(activationChar.length, lastPoint));
if (data.length > 0) data = data[0]; else data = {};
// Indicate that autocompletion should start after the . (ignoring the first part)
startFrom = text.lastIndexOf('.') + 1;
data = jsonpath.query(jsonObj, '$.' + text.substring(activationChar.length, lastPoint))
if (data.length > 0) {
data = data[0]
} else {
data = {}
}
// Indicate that autocompletion should start after the . (ignoring the first part)
startFrom = text.lastIndexOf('.') + 1
} else {
data = jsonObj
}
else
data = jsonObj;
var optionsStr = YaskON.stringify(data, null, activationChar);
var options = optionsStr.split('\n');
return { startFrom: startFrom, options: options };
const optionsStr = YaskON.stringify(data, null, activationChar)
const options = optionsStr.split('\n')
return { startFrom: startFrom, options: options }
}
}
};
}
// helper function to auto complete paths of a JSON object
var YaskON = {
const YaskON = {
// Return first level json paths by the node 'o'
stringify: function (o, prefix, activationChar) {
prefix = prefix || '';
prefix = prefix || ''
switch (typeof o) {
case 'object':
var output = '';
let output = ''
if (Array.isArray(o)) {
o.forEach(function (e, index) {
output += activationChar + prefix + '[' + index + ']' + '\n';
}.bind(this));
return output;
output += activationChar + prefix + '[' + index + ']' + '\n'
}.bind(this))
return output
}
output = '';
for (var k in o) {
output = ''
for (let k in o) {
if (o.hasOwnProperty(k)) {
if (prefix === '') output += this.stringify(o[k], k, activationChar);
if (prefix === '') output += this.stringify(o[k], k, activationChar)
}
}
if (prefix !== '') output += activationChar + prefix + '\n'
return output;
return output
case 'function':
return '';
return ''
default:
return prefix + '\n';
return prefix + '\n'
}
}
};
}
var json = {
const json = {
'array': [{ 'field1': 'v1', 'field2': 'v2' }, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': { 'a': 'b', 'c': 'd' },
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -16,42 +16,42 @@
</head>
<body>
<p>
JSONEditor has support for multiple languages (i18n), in this case uses <code>pt-BR</code>.
</p>
<div id="jsoneditor"></div>
<p>
JSONEditor has support for multiple languages (i18n), in this case uses <code>pt-BR</code>.
</p>
<div id="jsoneditor"></div>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
// switch between pt-BR or en for testing forcing a language
// leave blank to get language
'language': 'pt-BR',
'languages': {
'pt-BR': {
'auto': 'Automático testing'
},
'en': {
'auto': 'Auto testing'
},
'newlang': {
'auto': 'Auto new lang'
}
<script>
// create the editor
const container = document.getElementById('jsoneditor')
const options = {
// switch between pt-BR or en for testing forcing a language
// leave blank to get language
'language': 'pt-BR',
'languages': {
'pt-BR': {
'auto': 'Automático testing'
},
'en': {
'auto': 'Auto testing'
},
'newlang': {
'auto': 'Auto new lang'
}
};
var editor = new JSONEditor(container, options);
}
}
const editor = new JSONEditor(container, options)
var json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': { 'a': 'b', 'c': 'd' },
'string': 'Hello World'
};
editor.set(json);
</script>
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': { 'a': 'b', 'c': 'd' },
'string': 'Hello World'
}
editor.set(json)
</script>
</body>
</html>

View File

@ -58,52 +58,50 @@
</form>
<script>
var container, options, json, editor;
const container = document.getElementById('jsoneditor')
container = document.getElementById('jsoneditor');
options = {
const options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onChange: function () {
console.log('change');
console.log('change')
},
onModeChange: function (mode) {
var treeMode = document.getElementById('treeModeSelection');
var textMode = document.getElementById('textModeSelection');
const treeMode = document.getElementById('treeModeSelection')
const textMode = document.getElementById('textModeSelection')
treeMode.style.display = textMode.style.display = 'none';
treeMode.style.display = textMode.style.display = 'none'
if (mode === 'code' || mode === 'text') {
textMode.style.display = 'inline';
textMode.style.display = 'inline'
} else {
treeMode.style.display = 'inline';
treeMode.style.display = 'inline'
}
},
indentation: 4,
escapeUnicode: true,
onTextSelectionChange: function(start, end, text) {
var rangeEl = document.getElementById('textRange');
rangeEl.innerHTML = 'start: ' + JSON.stringify(start) + ', end: ' + JSON.stringify(end);
var textEl = document.getElementById('selectedText');
textEl.innerHTML = text;
const rangeEl = document.getElementById('textRange')
rangeEl.innerHTML = 'start: ' + JSON.stringify(start) + ', end: ' + JSON.stringify(end)
const textEl = document.getElementById('selectedText')
textEl.innerHTML = text
},
onSelectionChange: function(start, end) {
var nodesEl = document.getElementById('selectedNodes');
nodesEl.innerHTML = '';
const nodesEl = document.getElementById('selectedNodes')
nodesEl.innerHTML = ''
if (start) {
nodesEl.innerHTML = ('start: ' + JSON.stringify(start));
nodesEl.innerHTML = ('start: ' + JSON.stringify(start))
if (end) {
nodesEl.innerHTML += ('<br/>end: ' + JSON.stringify(end));
nodesEl.innerHTML += ('<br/>end: ' + JSON.stringify(end))
}
}
}
};
}
json = {
const json = {
"array": [1, 2, [3,4,5]],
"boolean": true,
"htmlcode": '&quot;',
@ -115,12 +113,12 @@
"object": {"a": "b", "c": "d"},
"string": "Hello World",
"url": "http://jsoneditoronline.org"
};
}
window.editor = new JSONEditor(container, options, json);
window.editor = new JSONEditor(container, options, json)
console.log('json', json);
console.log('string', JSON.stringify(json));
console.log('json', json)
console.log('string', JSON.stringify(json))
</script>
</body>
</html>

View File

@ -35,30 +35,30 @@
<script>
// create editor 1
var editor1 = new JSONEditor(document.getElementById('jsoneditor1'), {
const editor1 = new JSONEditor(document.getElementById('jsoneditor1'), {
onChangeText: function (jsonString) {
editor2.updateText(jsonString);
editor2.updateText(jsonString)
}
});
})
// create editor 2
var editor2 = new JSONEditor(document.getElementById('jsoneditor2'), {
const editor2 = new JSONEditor(document.getElementById('jsoneditor2'), {
onChangeText: function (jsonString) {
editor1.updateText(jsonString);
editor1.updateText(jsonString)
}
});
})
// set initial data in both editors
var json = {
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
editor1.set(json);
editor2.set(json);
}
editor1.set(json)
editor2.set(json)
</script>
</body>
</html>

View File

@ -37,42 +37,42 @@
</form>
<script>
var container, options, json;
const container = document.getElementById('jsoneditor')
container = document.getElementById('jsoneditor');
options = {
const options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
name: "jsonContent",
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onEvent: function(node, event) {
if (event.type === 'click') {
var message = 'click on <' + node.field +
let message = 'click on <' + node.field +
'> under path <' + node.path +
'> with pretty path: <' + prettyPrintPath(node.path) + '>';
if (node.value) message += ' with value <' + node.value + '>';
console.log(message);
'> with pretty path: <' + prettyPrintPath(node.path) + '>'
if (node.value) {
message += ' with value <' + node.value + '>'
}
console.log(message)
}
function prettyPrintPath(path) {
var str = '';
for (var i=0; i<path.length; i++) {
var element = path[i];
let str = ''
for (let i=0; i<path.length; i++) {
const element = path[i]
if (typeof element === 'number') {
str += '[' + element + ']'
} else {
if (str.length > 0) str += ',';
str += element;
if (str.length > 0) str += ','
str += element
}
}
return str;
return str
}
}
};
}
json = {
const json = {
"array": [1, 2, [3,4,5]],
"boolean": true,
"htmlcode": '&quot;',
@ -85,12 +85,12 @@
"string": "Hello World",
"url": "http://jsoneditoronline.org",
"[0]": "zero"
};
}
window.editor = new JSONEditor(container, options, json);
window.editor = new JSONEditor(container, options, json)
console.log('json', json);
console.log('string', JSON.stringify(json));
console.log('json', json)
console.log('string', JSON.stringify(json))
</script>
</body>
</html>

View File

@ -28,7 +28,7 @@
<div id="jsoneditor"></div>
<script>
var json = {
const json = {
team: [
{
name: 'Joe',
@ -42,9 +42,9 @@
name: 'Jack'
}
]
};
}
var options = {
const options = {
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview'],
onValidate: function (json) {
@ -52,59 +52,56 @@
// - team, names, and ages must be filled in and be of correct type
// - a team must have 4 members
// - at lease one member of the team must be adult
var errors = [];
const errors = []
if (json && Array.isArray(json.team)) {
// check whether each team member has name and age filled in correctly
json.team.forEach(function (member, index) {
if (typeof member !== 'object') {
errors.push({ path: ['team', index], message: 'Member must be an object with properties "name" and "age"' })
errors.push({path: ['team', index], message: 'Member must be an object with properties "name" and "age"'})
}
if ('name' in member) {
if (typeof member.name !== 'string') {
errors.push({ path: ['team', index, 'name'], message: 'Name must be a string' })
errors.push({path: ['team', index, 'name'], message: 'Name must be a string'})
}
}
else {
errors.push({ path: ['team', index], message: 'Required property "name"" missing' })
} else {
errors.push({path: ['team', index], message: 'Required property "name"" missing'})
}
if ('age' in member) {
if (typeof member.age !== 'number') {
errors.push({ path: ['team', index, 'age'], message: 'Age must be a number' })
errors.push({path: ['team', index, 'age'], message: 'Age must be a number'})
}
} else {
errors.push({path: ['team', index], message: 'Required property "age" missing'})
}
else {
errors.push({ path: ['team', index], message: 'Required property "age" missing' })
}
});
})
// check whether the team consists of exactly four members
if (json.team.length !== 4) {
errors.push({ path: ['team'], message: 'A team must have 4 members' })
errors.push({path: ['team'], message: 'A team must have 4 members'})
}
// check whether there is at least one adult member in the team
var adults = json.team.filter(function (member) {
return member ? member.age >= 18 : false;
});
const adults = json.team.filter(function (member) {
return member ? member.age >= 18 : false
})
if (adults.length === 0) {
errors.push({ path: ['team'], message: 'A team must have at least one adult person (age >= 18)' })
errors.push({path: ['team'], message: 'A team must have at least one adult person (age >= 18)'})
}
}
else {
errors.push({ path: [], message: 'Required property "team" missing or not an Array' })
} else {
errors.push({path: [], message: 'Required property "team" missing or not an Array'})
}
return errors;
return errors
}
};
}
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
editor.expandAll();
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
</script>
</body>
</html>

View File

@ -29,15 +29,15 @@
<div id="jsoneditor"></div>
<script>
var json = {
const json = {
customers: [
{name: 'Joe'},
{name: 'Sarah'},
{name: 'Harry'},
]
};
}
var options = {
const options = {
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview'],
onValidate: function (json) {
@ -54,35 +54,35 @@
}
}
else {
return null;
return null
}
});
})
}))
.then(function (errors) {
return errors.filter(function (error) {
return error != null;
return error != null
})
});
})
}
else {
return null;
return null
}
}
};
}
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
editor.expandAll();
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
// this function fakes a request (asynchronous) to a server to validate the existence of a customer
function isExistingCustomer (customerName) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
var customers = ['Joe', 'Harry', 'Megan'];
var exists = customers.indexOf(customerName) !== -1;
resolve(exists);
}, 500);
const customers = ['Joe', 'Harry', 'Megan']
const exists = customers.indexOf(customerName) !== -1
resolve(exists)
}, 500)
})
}
</script>

View File

@ -52,66 +52,66 @@
</div>
<script>
var containerLeft = document.getElementById('containerLeft');
var containerRight = document.getElementById('containerRight');
const containerLeft = document.getElementById('containerLeft')
const containerRight = document.getElementById('containerRight')
function findNodeInJson(json, path){
if(!json || path.length ===0) {
return {field: undefined, value: undefined}
}
var first = path[0];
var remainingPath = path.slice(1);
const first = path[0]
const remainingPath = path.slice(1)
if(remainingPath.length === 0) {
return {field: (typeof json[first] !== 'undefined' ? first : undefined), value: json[first]};
return {field: (typeof json[first] !== 'undefined' ? first : undefined), value: json[first]}
} else {
return findNodeInJson(json[first], remainingPath)
}
}
function onClassName({ path, field, value }) {
var thisNode = findNodeInJson(jsonRight, path);
var oppositeNode = findNodeInJson(jsonLeft, path);
var isValueEqual = JSON.stringify(thisNode.value) === JSON.stringify(oppositeNode.value);
const thisNode = findNodeInJson(jsonRight, path)
const oppositeNode = findNodeInJson(jsonLeft, path)
let isValueEqual = JSON.stringify(thisNode.value) === JSON.stringify(oppositeNode.value)
if(Array.isArray(thisNode.value) && Array.isArray(oppositeNode.value)) {
isValueEqual = thisNode.value.every(function (e) {
return oppositeNode.value.includes(e);
return oppositeNode.value.includes(e)
})
}
if (thisNode.field === oppositeNode.field && isValueEqual) {
return 'the_same_element';
return 'the_same_element'
} else {
return 'different_element'
}
}
var optionsLeft = {
const optionsLeft = {
mode: 'tree',
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onClassName: onClassName,
onChangeJSON: function (j) {
jsonLeft = j;
jsonLeft = j
window.editorRight.refresh()
}
};
}
var optionsRight = {
const optionsRight = {
mode: 'tree',
onError: function (err) {
alert(err.toString());
alert(err.toString())
},
onClassName: onClassName,
onChangeJSON: function (j) {
jsonRight = j;
window.editorLeft.refresh();
jsonRight = j
window.editorLeft.refresh()
}
};
}
var jsonLeft = {
let jsonLeft = {
"arrayOfArrays": [1, 2, 999, [3,4,5]],
"someField": true,
"boolean": true,
@ -126,9 +126,9 @@
"string": "Hello World",
"url": "http://jsoneditoronline.org",
"[0]": "zero"
};
}
var jsonRight = {
let jsonRight = {
"arrayOfArrays": [1, 2, [3,4,5]],
"boolean": true,
"htmlcode": '&quot;',
@ -142,10 +142,10 @@
"string": "Hello World",
"url": "http://jsoneditoronline.org",
"[0]": "zero"
};
}
window.editorLeft = new JSONEditor(containerLeft, optionsLeft, jsonLeft);
window.editorRight = new JSONEditor(containerRight, optionsRight, jsonRight);
window.editorLeft = new JSONEditor(containerLeft, optionsLeft, jsonLeft)
window.editorRight = new JSONEditor(containerRight, optionsRight, jsonRight)
</script>
</body>
</html>

View File

@ -7,47 +7,44 @@
<script src="../dist/jsoneditor.js"></script>
<style type="text/css">
#jsoneditor {
width: 500px;
height: 500px;
}
#jsoneditor {
width: 500px;
height: 500px;
}
.submenu-highlight { background-color: yellow !important; }
.submenu-highlight {
background-color: yellow !important;
}
.rainbow {
.rainbow {
background: linear-gradient(to right, cyan, yellow, violet, green, orange, blue) !important;
}
background: linear-gradient(to right, cyan, yellow, violet, green, orange, blue) !important;
}
.example-class > .jsoneditor-icon {
background-position: -168px -48px; /* warning triangle */
}
.dotty {
border-top : 1px dotted #e5e5e5 !important;
}
.example-class > .jsoneditor-icon {
background-position: -168px -48px; /* warning triangle */
}
.dotty {
border-top : 1px dotted #e5e5e5 !important;
}
</style>
</head>
<body>
<h1>Context Menu Customization</h1>
<p>
This example demonstrates the use of the onCreateMenu callback option, which
allows you to customise context menus after they are created but before they
are shown to the user. You can alter/delete existing items as well as
adding new menu items. See the source code for this example for more
information.
</p>
<div id="jsoneditor"></div>
<h1>Context Menu Customization</h1>
<p>
This example demonstrates the use of the onCreateMenu callback option, which
allows you to customise context menus after they are created but before they
are shown to the user. You can alter/delete existing items as well as
adding new menu items. See the source code for this example for more
information.
</p>
<div id="jsoneditor"></div>
<script>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
const container = document.getElementById('jsoneditor')
const options = {
// onCreateMenu allows us to register a call back function to customise
// the context menu. The callback accpets two parameters, items and path.
// Items is an array containing the current menu items, and path
@ -58,11 +55,11 @@
// Every time the user clicks on a context menu button, the menu
// is created from scratch and this callback is called.
onCreateMenu : function (items, node) {
var path = node.path
onCreateMenu: function (items, node) {
const path = node.path
// log the current items and node for inspection
console.log('items:', items, 'node:', node);
console.log('items:', items, 'node:', node)
// We are going to add a menu item which returns the current node path
// as a jq path selector ( https://stedolan.github.io/jq/ ). First we
@ -70,69 +67,49 @@
// the menu item click property in a moment.
function pathTojq() {
var pathString = '';
let pathString = ''
path.forEach(function (segment, index) { // path is an array, loop through it
if ( typeof segment == 'number') { // format the selector for array indexs ...
pathString += '[' + segment + ']';
if (typeof segment == 'number') { // format the selector for array indexs ...
pathString += '[' + segment + ']'
} else { // ... or object keys
pathString += '."' + segment + '"';
pathString += '."' + segment + '"'
}
})
alert(pathString); // show it to the user.
};
alert(pathString) // show it to the user.
}
// Create a new menu item. For our example, we only want to do this
// if there is a path (in the case of appendnodes (for new objects)
// path is null until a node is created)
if (path) {
// Each item in the items array represents a menu item,
// and requires the following details :
items.push( {
items.push({
text: 'jq Path', // the text for the menu item
title: 'Show the jq path for this node', // the HTML title attribute
className: 'example-class', // the css class name(s) for the menu item
click: pathTojq // the function to call when the menu item is clicked
})
}
text : 'jq Path', // the text for the menu item
title : 'Show the jq path for this node', // the HTML title attribute
className : 'example-class', // the css class name(s) for the menu item
click : pathTojq // the function to call when the menu item is clicked
} );
};
// Now we will iterate through the menu items, which includes the items
// created by jsoneditor, and the new item we added above. In this
// example we will just alter the className property for the items, but
// you can alter any property (e.g. the click callback, text property etc.)
// for any item, or even delete the whole menu item.
items.forEach(function (item, index, items) {
if ( "submenu" in item ) {
if ("submenu" in item) {
// if the item has a submenu property, it is a submenu heading
// and contains another array of menu items. Let's colour
// that yellow...
items[index].className += ' submenu-highlight';
items[index].className += ' submenu-highlight'
} else {
// if it's not a submenu heading, let's make it colorful
items[index].className += ' rainbow';
items[index].className += ' rainbow'
}
})
@ -143,20 +120,17 @@
// next, just for fun, let's remove any menu separators (again just at the
// top level menu). A menu separator is an item with a type : 'separator'
// property
items = items.filter(function (item) {
return item.type !== 'separator';
});
return item.type !== 'separator'
})
// finally we need to return the items array. If we don't, the menu
// will be empty.
return items;
return items
}
};
}
var json = {
const json = {
'array': [1, 2, 3],
'boolean': true,
'color': '#82b92c',
@ -164,10 +138,9 @@
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
};
var editor = new JSONEditor(container, options, json);
}
const editor = new JSONEditor(container, options, json)
</script>
</body>
</html>

View File

@ -1,12 +1,12 @@
var module = '../../../dist/jsoneditor'
const module = '../../../dist/jsoneditor'
require([module], function (JSONEditor) {
// create the editor
var container = document.getElementById('jsoneditor')
var editor = new JSONEditor(container)
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container)
// set json
document.getElementById('setJSON').onclick = function () {
var json = {
const json = {
array: [1, 2, 3],
boolean: true,
null: null,
@ -19,7 +19,7 @@ require([module], function (JSONEditor) {
// get json
document.getElementById('getJSON').onclick = function () {
var json = editor.get()
const json = editor.get()
window.alert(JSON.stringify(json, null, 2))
}
})