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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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