From 531ddc5c74364744d8e8cb988206a85f90e8cf09 Mon Sep 17 00:00:00 2001 From: jos Date: Wed, 28 Aug 2019 13:37:27 +0200 Subject: [PATCH] Run lebab: convert let/const and arrow functions --- src/js/ContextMenu.js | 102 ++--- src/js/ErrorTable.js | 42 +- src/js/Highlighter.js | 4 +- src/js/History.js | 10 +- src/js/JSONEditor.js | 52 +-- src/js/ModeSwitcher.js | 26 +- src/js/Node.js | 808 ++++++++++++++++----------------- src/js/NodeHistory.js | 98 ++-- src/js/SearchBox.js | 66 +-- src/js/TreePath.js | 28 +- src/js/ace/index.js | 2 +- src/js/ace/theme-jsoneditor.js | 4 +- src/js/appendNodeFactory.js | 58 ++- src/js/autocomplete.js | 76 ++-- src/js/createAbsoluteAnchor.js | 22 +- src/js/i18n.js | 26 +- src/js/jsonUtils.js | 24 +- src/js/polyfills.js | 6 +- src/js/previewmode.js | 137 +++--- src/js/showMoreNodeFactory.js | 26 +- src/js/showSortModal.js | 34 +- src/js/showTransformModal.js | 108 +++-- src/js/textmode.js | 206 ++++----- src/js/treemode.js | 369 +++++++-------- src/js/util.js | 345 +++++++------- src/js/validationUtils.js | 24 +- src/js/vanilla-picker/index.js | 2 +- 27 files changed, 1310 insertions(+), 1395 deletions(-) diff --git a/src/js/ContextMenu.js b/src/js/ContextMenu.js index f3a0dc9..de0d00f 100644 --- a/src/js/ContextMenu.js +++ b/src/js/ContextMenu.js @@ -1,8 +1,8 @@ 'use strict' -var createAbsoluteAnchor = require('./createAbsoluteAnchor').createAbsoluteAnchor -var util = require('./util') -var translate = require('./i18n').translate +const createAbsoluteAnchor = require('./createAbsoluteAnchor').createAbsoluteAnchor +const util = require('./util') +const translate = require('./i18n').translate /** * A context menu @@ -16,8 +16,8 @@ var translate = require('./i18n').translate function ContextMenu (items, options) { this.dom = {} - var me = this - var dom = this.dom + const me = this + const dom = this.dom this.anchor = undefined this.items = items this.eventListeners = {} @@ -25,51 +25,51 @@ function ContextMenu (items, options) { this.onClose = options ? options.close : undefined // create root element - var root = document.createElement('div') + const root = document.createElement('div') root.className = 'jsoneditor-contextmenu-root' dom.root = root // create a container element - var menu = document.createElement('div') + const menu = document.createElement('div') menu.className = 'jsoneditor-contextmenu' dom.menu = menu root.appendChild(menu) // create a list to hold the menu items - var list = document.createElement('ul') + const list = document.createElement('ul') list.className = 'jsoneditor-menu' menu.appendChild(list) dom.list = list dom.items = [] // list with all buttons // create a (non-visible) button to set the focus to the menu - var focusButton = document.createElement('button') + const focusButton = document.createElement('button') focusButton.type = 'button' dom.focusButton = focusButton - var li = document.createElement('li') + const li = document.createElement('li') li.style.overflow = 'hidden' li.style.height = '0' li.appendChild(focusButton) list.appendChild(li) function createMenuItems (list, domItems, items) { - items.forEach(function (item) { + items.forEach(item => { if (item.type === 'separator') { // create a separator - var separator = document.createElement('div') + const separator = document.createElement('div') separator.className = 'jsoneditor-separator' const li = document.createElement('li') li.appendChild(separator) list.appendChild(li) } else { - var domItem = {} + const domItem = {} // create a menu item const li = document.createElement('li') list.appendChild(li) // create a button in the menu item - var button = document.createElement('button') + const button = document.createElement('button') button.type = 'button' button.className = item.className domItem.button = button @@ -77,7 +77,7 @@ function ContextMenu (items, options) { button.title = item.title } if (item.click) { - button.onclick = function (event) { + button.onclick = event => { event.preventDefault() me.hide() item.click() @@ -88,21 +88,21 @@ function ContextMenu (items, options) { // create the contents of the button if (item.submenu) { // add the icon to the button - var divIcon = document.createElement('div') + const divIcon = document.createElement('div') divIcon.className = 'jsoneditor-icon' button.appendChild(divIcon) - var divText = document.createElement('div') + const divText = document.createElement('div') divText.className = 'jsoneditor-text' + (item.click ? '' : ' jsoneditor-right-margin') divText.appendChild(document.createTextNode(item.text)) button.appendChild(divText) - var buttonSubmenu + let buttonSubmenu if (item.click) { // submenu and a button with a click handler button.className += ' jsoneditor-default' - var buttonExpand = document.createElement('button') + const buttonExpand = document.createElement('button') buttonExpand.type = 'button' domItem.buttonExpand = buttonExpand buttonExpand.className = 'jsoneditor-expand' @@ -115,7 +115,7 @@ function ContextMenu (items, options) { buttonSubmenu = buttonExpand } else { // submenu and a button without a click handler - var divExpand = document.createElement('div') + const divExpand = document.createElement('div') divExpand.className = 'jsoneditor-expand' button.appendChild(divExpand) @@ -123,16 +123,16 @@ function ContextMenu (items, options) { } // attach a handler to expand/collapse the submenu - buttonSubmenu.onclick = function (event) { + buttonSubmenu.onclick = event => { event.preventDefault() me._onExpandItem(domItem) buttonSubmenu.focus() } // create the submenu - var domSubItems = [] + const domSubItems = [] domItem.subItems = domSubItems - var ul = document.createElement('ul') + const ul = document.createElement('ul') domItem.ul = ul ul.className = 'jsoneditor-menu' ul.style.height = '0' @@ -154,8 +154,8 @@ function ContextMenu (items, options) { // calculate the max height of the menu with one submenu expanded this.maxHeight = 0 // height in pixels - items.forEach(function (item) { - var height = (items.length + (item.submenu ? item.submenu.length : 0)) * 24 + items.forEach(item => { + const height = (items.length + (item.submenu ? item.submenu.length : 0)) * 24 me.maxHeight = Math.max(me.maxHeight, height) }) } @@ -166,15 +166,15 @@ function ContextMenu (items, options) { * @private */ ContextMenu.prototype._getVisibleButtons = function () { - var buttons = [] - var me = this - this.dom.items.forEach(function (item) { + const buttons = [] + const me = this + this.dom.items.forEach(item => { buttons.push(item.button) if (item.buttonExpand) { buttons.push(item.buttonExpand) } if (item.subItems && item === me.expandedItem) { - item.subItems.forEach(function (subItem) { + item.subItems.forEach(subItem => { buttons.push(subItem.button) if (subItem.buttonExpand) { buttons.push(subItem.buttonExpand) @@ -200,14 +200,14 @@ ContextMenu.prototype.show = function (anchor, frame, ignoreParent) { this.hide() // determine whether to display the menu below or above the anchor - var showBelow = true - var parent = anchor.parentNode - var anchorRect = anchor.getBoundingClientRect() - var parentRect = parent.getBoundingClientRect() - var frameRect = frame.getBoundingClientRect() + let showBelow = true + const parent = anchor.parentNode + const anchorRect = anchor.getBoundingClientRect() + const parentRect = parent.getBoundingClientRect() + const frameRect = frame.getBoundingClientRect() - var me = this - this.dom.absoluteAnchor = createAbsoluteAnchor(anchor, frame, function () { + const me = this + this.dom.absoluteAnchor = createAbsoluteAnchor(anchor, frame, () => { me.hide() }) @@ -220,12 +220,12 @@ ContextMenu.prototype.show = function (anchor, frame, ignoreParent) { // doesn't fit above nor below -> show below } - var topGap = ignoreParent ? 0 : (anchorRect.top - parentRect.top) + const topGap = ignoreParent ? 0 : (anchorRect.top - parentRect.top) // position the menu if (showBelow) { // display the menu below the anchor - var anchorHeight = anchor.offsetHeight + const anchorHeight = anchor.offsetHeight this.dom.menu.style.left = '0' this.dom.menu.style.top = topGap + anchorHeight + 'px' this.dom.menu.style.bottom = '' @@ -243,7 +243,7 @@ ContextMenu.prototype.show = function (anchor, frame, ignoreParent) { // move focus to the first button in the context menu this.selection = util.getSelection() this.anchor = anchor - setTimeout(function () { + setTimeout(() => { me.dom.focusButton.focus() }, 0) @@ -283,16 +283,16 @@ ContextMenu.prototype.hide = function () { * @private */ ContextMenu.prototype._onExpandItem = function (domItem) { - var me = this - var alreadyVisible = (domItem === this.expandedItem) + const me = this + const alreadyVisible = (domItem === this.expandedItem) // hide the currently visible submenu - var expandedItem = this.expandedItem + const expandedItem = this.expandedItem if (expandedItem) { // var ul = expandedItem.ul; expandedItem.ul.style.height = '0' expandedItem.ul.style.padding = '' - setTimeout(function () { + setTimeout(() => { if (me.expandedItem !== expandedItem) { expandedItem.ul.style.display = '' util.removeClassName(expandedItem.ul.parentNode, 'jsoneditor-selected') @@ -302,14 +302,14 @@ ContextMenu.prototype._onExpandItem = function (domItem) { } if (!alreadyVisible) { - var ul = domItem.ul + const ul = domItem.ul ul.style.display = 'block' // eslint-disable-next-line no-unused-expressions ul.clientHeight // force a reflow in Firefox - setTimeout(function () { + setTimeout(() => { if (me.expandedItem === domItem) { - var childsHeight = 0 - for (var i = 0; i < ul.childNodes.length; i++) { + let childsHeight = 0 + for (let i = 0; i < ul.childNodes.length; i++) { childsHeight += ul.childNodes[i].clientHeight } ul.style.height = childsHeight + 'px' @@ -327,10 +327,10 @@ ContextMenu.prototype._onExpandItem = function (domItem) { * @private */ ContextMenu.prototype._onKeyDown = function (event) { - var target = event.target - var keynum = event.which - var handled = false - var buttons, targetIndex, prevButton, nextButton + const target = event.target + const keynum = event.which + let handled = false + let buttons, targetIndex, prevButton, nextButton if (keynum === 27) { // ESC // hide the menu on ESC key diff --git a/src/js/ErrorTable.js b/src/js/ErrorTable.js index 3ea30b5..3675467 100644 --- a/src/js/ErrorTable.js +++ b/src/js/ErrorTable.js @@ -10,28 +10,28 @@ function ErrorTable (config) { this.errorTableVisible = config.errorTableVisible this.onToggleVisibility = config.onToggleVisibility - this.onFocusLine = config.onFocusLine || function () {} + this.onFocusLine = config.onFocusLine || (() => {}) this.onChangeHeight = config.onChangeHeight this.dom = {} - var validationErrorsContainer = document.createElement('div') + const validationErrorsContainer = document.createElement('div') validationErrorsContainer.className = 'jsoneditor-validation-errors-container' this.dom.validationErrorsContainer = validationErrorsContainer - var additionalErrorsIndication = document.createElement('div') + const additionalErrorsIndication = document.createElement('div') additionalErrorsIndication.style.display = 'none' additionalErrorsIndication.className = 'jsoneditor-additional-errors fadein' additionalErrorsIndication.innerHTML = 'Scroll for more ▿' this.dom.additionalErrorsIndication = additionalErrorsIndication validationErrorsContainer.appendChild(additionalErrorsIndication) - var validationErrorIcon = document.createElement('span') + const validationErrorIcon = document.createElement('span') validationErrorIcon.className = 'jsoneditor-validation-error-icon' validationErrorIcon.style.display = 'none' this.dom.validationErrorIcon = validationErrorIcon - var validationErrorCount = document.createElement('span') + const validationErrorCount = document.createElement('span') validationErrorCount.className = 'jsoneditor-validation-error-count' validationErrorCount.style.display = 'none' this.dom.validationErrorCount = validationErrorCount @@ -63,7 +63,7 @@ ErrorTable.prototype.toggleTableVisibility = function () { } ErrorTable.prototype.setErrors = function (errors, errorLocations) { - var me = this + const me = this // clear any previous errors if (this.dom.validationErrors) { @@ -75,13 +75,13 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { // create the table with errors // keep default behavior for parse errors if (this.errorTableVisible && errors.length > 0) { - var validationErrors = document.createElement('div') + const validationErrors = document.createElement('div') validationErrors.className = 'jsoneditor-validation-errors' validationErrors.innerHTML = '
' - var tbody = validationErrors.getElementsByTagName('tbody')[0] + const tbody = validationErrors.getElementsByTagName('tbody')[0] - errors.forEach(function (error) { - var message + errors.forEach(error => { + let message if (typeof error === 'string') { message = '
' + error + '
' } else { @@ -90,18 +90,18 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { '
' + error.message + '
' } - var line + let line if (!isNaN(error.line)) { line = error.line } else if (error.dataPath) { - var errLoc = errorLocations.find(function (loc) { return loc.path === error.dataPath }) + const errLoc = errorLocations.find(loc => loc.path === error.dataPath) if (errLoc) { line = errLoc.line + 1 } } - var trEl = document.createElement('tr') + const trEl = document.createElement('tr') trEl.className = !isNaN(line) ? 'jump-to-line' : '' if (error.type === 'error') { trEl.className += ' parse-error' @@ -110,7 +110,7 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { } trEl.innerHTML = ('' + (!isNaN(line) ? ('Ln ' + line) : '') + '' + message) - trEl.onclick = function () { + trEl.onclick = () => { me.onFocusLine(line) } @@ -123,7 +123,7 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { if (this.dom.validationErrorsContainer.clientHeight < this.dom.validationErrorsContainer.scrollHeight) { this.dom.additionalErrorsIndication.style.display = 'block' - this.dom.validationErrorsContainer.onscroll = function () { + this.dom.validationErrorsContainer.onscroll = () => { me.dom.additionalErrorsIndication.style.display = (me.dom.validationErrorsContainer.clientHeight > 0 && me.dom.validationErrorsContainer.scrollTop === 0) ? 'block' : 'none' } @@ -131,7 +131,7 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { this.dom.validationErrorsContainer.onscroll = undefined } - var height = this.dom.validationErrorsContainer.clientHeight + (this.dom.statusBar ? this.dom.statusBar.clientHeight : 0) + const height = this.dom.validationErrorsContainer.clientHeight + (this.dom.statusBar ? this.dom.statusBar.clientHeight : 0) // this.content.style.marginBottom = (-height) + 'px'; // this.content.style.paddingBottom = height + 'px'; this.onChangeHeight(height) @@ -140,9 +140,7 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { } // update the status bar - var validationErrorsCount = errors.filter(function (error) { - return error.type !== 'error' - }).length + const validationErrorsCount = errors.filter(error => error.type !== 'error').length if (validationErrorsCount > 0) { this.dom.validationErrorCount.style.display = 'inline' this.dom.validationErrorCount.innerText = validationErrorsCount @@ -157,11 +155,9 @@ ErrorTable.prototype.setErrors = function (errors, errorLocations) { } // update the parse error icon - var hasParseErrors = errors.some(function (error) { - return error.type === 'error' - }) + const hasParseErrors = errors.some(error => error.type === 'error') if (hasParseErrors) { - var line = errors[0].line + const line = errors[0].line this.dom.parseErrorIndication.style.display = 'block' this.dom.parseErrorIndication.title = !isNaN(line) ? ('parse error on line ' + line) diff --git a/src/js/Highlighter.js b/src/js/Highlighter.js index 7694e60..ba18b98 100644 --- a/src/js/Highlighter.js +++ b/src/js/Highlighter.js @@ -42,14 +42,14 @@ Highlighter.prototype.unhighlight = function () { return } - var me = this + const me = this if (this.node) { this._cancelUnhighlight() // do the unhighlighting after a small delay, to prevent re-highlighting // the same node when moving from the drag-icon to the contextmenu-icon // or vice versa. - this.unhighlightTimer = setTimeout(function () { + this.unhighlightTimer = setTimeout(() => { me.node.setHighlight(false) me.node = undefined me.unhighlightTimer = undefined diff --git a/src/js/History.js b/src/js/History.js index 3b1adfd..f7b2a2c 100644 --- a/src/js/History.js +++ b/src/js/History.js @@ -8,9 +8,7 @@ */ function History (onChange, calculateItemSize, limit) { this.onChange = onChange - this.calculateItemSize = calculateItemSize || function () { - return 1 - } + this.calculateItemSize = calculateItemSize || (() => 1) this.limit = limit this.items = [] @@ -35,10 +33,10 @@ History.prototype.add = function (item) { } History.prototype._calculateHistorySize = function () { - var calculateItemSize = this.calculateItemSize - var totalSize = 0 + const calculateItemSize = this.calculateItemSize + let totalSize = 0 - this.items.forEach(function (item) { + this.items.forEach(item => { totalSize += calculateItemSize(item) }) diff --git a/src/js/JSONEditor.js b/src/js/JSONEditor.js index 6736445..753b1d3 100644 --- a/src/js/JSONEditor.js +++ b/src/js/JSONEditor.js @@ -1,19 +1,19 @@ 'use strict' -var Ajv +let Ajv try { Ajv = require('ajv') } catch (err) { // no problem... when we need Ajv we will throw a neat exception } -var ace = require('./ace') // may be undefined in case of minimalist bundle -var VanillaPicker = require('./vanilla-picker') // may be undefined in case of minimalist bundle +const ace = require('./ace') // may be undefined in case of minimalist bundle +const VanillaPicker = require('./vanilla-picker') // may be undefined in case of minimalist bundle -var treemode = require('./treemode') -var textmode = require('./textmode') -var previewmode = require('./previewmode') -var util = require('./util') +const treemode = require('./treemode') +const textmode = require('./textmode') +const previewmode = require('./previewmode') +const util = require('./util') if (typeof Promise === 'undefined') { console.error('Promise undefined. Please load a Promise polyfill in the browser in order to use JSONEditor') @@ -101,7 +101,7 @@ function JSONEditor (container, options, json) { } // check for unsupported browser (IE8 and older) - var ieVersion = util.getInternetExplorerVersion() + const ieVersion = util.getInternetExplorerVersion() if (ieVersion !== -1 && ieVersion < 9) { throw new Error('Unsupported browser, IE9 or newer required. ' + 'Please install the newest version of your browser.') @@ -136,7 +136,7 @@ function JSONEditor (container, options, json) { // validate options if (options) { - Object.keys(options).forEach(function (option) { + Object.keys(options).forEach(option => { if (JSONEditor.VALID_OPTIONS.indexOf(option) === -1) { console.warn('Unknown option "' + option + '". This option will be ignored') } @@ -194,14 +194,14 @@ JSONEditor.prototype._create = function (container, options, json) { this.options = options || {} this.json = json || {} - var mode = this.options.mode || (this.options.modes && this.options.modes[0]) || 'tree' + const mode = this.options.mode || (this.options.modes && this.options.modes[0]) || 'tree' this.setMode(mode) } /** * Destroy the editor. Clean up DOM, event listeners, and web workers. */ -JSONEditor.prototype.destroy = function () {} +JSONEditor.prototype.destroy = () => {} /** * Set JSON object in editor @@ -266,17 +266,17 @@ JSONEditor.prototype.setMode = function (mode) { return } - var container = this.container - var options = util.extend({}, this.options) - var oldMode = options.mode - var data - var name + const container = this.container + const options = util.extend({}, this.options) + const oldMode = options.mode + let data + let name options.mode = mode - var config = JSONEditor.modes[mode] + const config = JSONEditor.modes[mode] if (config) { try { - var asText = (config.data === 'text') + const asText = (config.data === 'text') name = this.getName() data = this[asText ? 'getText' : 'get']() // get text or json @@ -343,7 +343,7 @@ JSONEditor.prototype._onError = function (err) { JSONEditor.prototype.setSchema = function (schema, schemaRefs) { // compile a JSON schema validator if a JSON schema is provided if (schema) { - var ajv + let ajv try { // grab ajv from options if provided, else create a new instance if (this.options.ajv) { @@ -366,7 +366,7 @@ JSONEditor.prototype.setSchema = function (schema, schemaRefs) { if (ajv) { if (schemaRefs) { - for (var ref in schemaRefs) { + for (const ref in schemaRefs) { ajv.removeSchema(ref) // When updating a schema - old refs has to be removed first if (schemaRefs[ref]) { ajv.addSchema(schemaRefs[ref], ref) @@ -399,14 +399,14 @@ JSONEditor.prototype.setSchema = function (schema, schemaRefs) { * Validate current JSON object against the configured JSON schema * Throws an exception when no JSON schema is configured */ -JSONEditor.prototype.validate = function () { +JSONEditor.prototype.validate = () => { // must be implemented by treemode and textmode } /** * Refresh the rendered contents */ -JSONEditor.prototype.refresh = function () { +JSONEditor.prototype.refresh = () => { // can be implemented by treemode and textmode } @@ -429,8 +429,8 @@ JSONEditor.prototype.refresh = function () { * * @param {Object | Array} mode A mode object or an array with multiple mode objects. */ -JSONEditor.registerMode = function (mode) { - var i, prop +JSONEditor.registerMode = mode => { + let i, prop if (util.isArray(mode)) { // multiple modes @@ -442,7 +442,7 @@ JSONEditor.registerMode = function (mode) { if (!('mode' in mode)) throw new Error('Property "mode" missing') if (!('mixin' in mode)) throw new Error('Property "mixin" missing') if (!('data' in mode)) throw new Error('Property "data" missing') - var name = mode.mode + const name = mode.mode if (name in JSONEditor.modes) { throw new Error('Mode "' + name + '" already registered') } @@ -451,7 +451,7 @@ JSONEditor.registerMode = function (mode) { if (typeof mode.mixin.create !== 'function') { throw new Error('Required function "create" missing on mixin') } - var reserved = ['setMode', 'registerMode', 'modes'] + const reserved = ['setMode', 'registerMode', 'modes'] for (i = 0; i < reserved.length; i++) { prop = reserved[i] if (prop in mode.mixin) { diff --git a/src/js/ModeSwitcher.js b/src/js/ModeSwitcher.js index a6acc63..4e0e5e8 100644 --- a/src/js/ModeSwitcher.js +++ b/src/js/ModeSwitcher.js @@ -1,7 +1,7 @@ 'use strict' -var ContextMenu = require('./ContextMenu') -var translate = require('./i18n').translate +const ContextMenu = require('./ContextMenu') +const translate = require('./i18n').translate /** * Create a select box to be used in the editor menu's, which allows to switch mode @@ -13,7 +13,7 @@ var translate = require('./i18n').translate */ function ModeSwitcher (container, modes, current, onSwitch) { // available modes - var availableModes = { + const availableModes = { code: { text: translate('modeCodeText'), title: translate('modeCodeTitle'), @@ -59,10 +59,10 @@ function ModeSwitcher (container, modes, current, onSwitch) { } // list the selected modes - var items = [] - for (var i = 0; i < modes.length; i++) { - var mode = modes[i] - var item = availableModes[mode] + const items = [] + for (let i = 0; i < modes.length; i++) { + const mode = modes[i] + const item = availableModes[mode] if (!item) { throw new Error('Unknown mode "' + mode + '"') } @@ -72,24 +72,24 @@ function ModeSwitcher (container, modes, current, onSwitch) { } // retrieve the title of current mode - var currentMode = availableModes[current] + const currentMode = availableModes[current] if (!currentMode) { throw new Error('Unknown mode "' + current + '"') } - var currentTitle = currentMode.text + const currentTitle = currentMode.text // create the html element - var box = document.createElement('button') + const box = document.createElement('button') box.type = 'button' box.className = 'jsoneditor-modes jsoneditor-separator' box.innerHTML = currentTitle + ' ▾' box.title = 'Switch editor mode' - box.onclick = function () { - var menu = new ContextMenu(items) + box.onclick = () => { + const menu = new ContextMenu(items) menu.show(box, container) } - var frame = document.createElement('div') + const frame = document.createElement('div') frame.className = 'jsoneditor-modes' frame.style.position = 'relative' frame.appendChild(box) diff --git a/src/js/Node.js b/src/js/Node.js index c9e196b..db78ab9 100644 --- a/src/js/Node.js +++ b/src/js/Node.js @@ -1,18 +1,18 @@ 'use strict' -var jmespath = require('jmespath') -var naturalSort = require('javascript-natural-sort') -var createAbsoluteAnchor = require('./createAbsoluteAnchor').createAbsoluteAnchor -var ContextMenu = require('./ContextMenu') -var appendNodeFactory = require('./appendNodeFactory') -var showMoreNodeFactory = require('./showMoreNodeFactory') -var showSortModal = require('./showSortModal') -var showTransformModal = require('./showTransformModal') -var util = require('./util') -var translate = require('./i18n').translate -var DEFAULT_MODAL_ANCHOR = require('./constants').DEFAULT_MODAL_ANCHOR +const jmespath = require('jmespath') +const naturalSort = require('javascript-natural-sort') +const createAbsoluteAnchor = require('./createAbsoluteAnchor').createAbsoluteAnchor +const ContextMenu = require('./ContextMenu') +const appendNodeFactory = require('./appendNodeFactory') +const showMoreNodeFactory = require('./showMoreNodeFactory') +const showSortModal = require('./showSortModal') +const showTransformModal = require('./showTransformModal') +const util = require('./util') +const translate = require('./i18n').translate +const DEFAULT_MODAL_ANCHOR = require('./constants').DEFAULT_MODAL_ANCHOR -var YEAR_2000 = 946684800000 +const YEAR_2000 = 946684800000 /** * @constructor Node @@ -58,7 +58,7 @@ Node.prototype.DEBOUNCE_INTERVAL = 150 Node.prototype.MAX_SEARCH_RESULTS = 999 // default number of child nodes to display -var DEFAULT_MAX_VISIBLE_CHILDS = 100 +const DEFAULT_MAX_VISIBLE_CHILDS = 100 Node.prototype.getMaxVisibleChilds = function () { return (this.editor && this.editor.options && this.editor.options.maxVisibleChilds) @@ -82,7 +82,7 @@ Node.prototype._updateEditability = function () { if ((this.editor.options.mode === 'tree' || this.editor.options.mode === 'form') && (typeof this.editor.options.onEditable === 'function')) { - var editable = this.editor.options.onEditable({ + const editable = this.editor.options.onEditable({ field: this.field, value: this.value, path: this.getPath() @@ -105,10 +105,10 @@ Node.prototype._updateEditability = function () { * Element is a number if is the index of an array, a string otherwise. */ Node.prototype.getPath = function () { - var node = this - var path = [] + let node = this + const path = [] while (node) { - var field = node.getName() + const field = node.getName() if (field !== undefined) { path.unshift(field) } @@ -122,8 +122,8 @@ Node.prototype.getPath = function () { * @return {String[]} Array containing the internal path to this node */ Node.prototype.getInternalPath = function () { - var node = this - var internalPath = [] + let node = this + const internalPath = [] while (node) { if (node.parent) { internalPath.unshift(node.getIndex()) @@ -159,7 +159,7 @@ Node.prototype.findNodeByPath = function (path) { } if (path.length && this.childs && this.childs.length) { - for (var i = 0; i < this.childs.length; ++i) { + for (let i = 0; i < this.childs.length; ++i) { if (('' + path[0]) === ('' + this.childs[i].getName())) { return this.childs[i].findNodeByPath(path.slice(1)) } @@ -178,9 +178,9 @@ Node.prototype.findNodeByInternalPath = function (internalPath) { return undefined } - var node = this - for (var i = 0; i < internalPath.length && node; i++) { - var childIndex = internalPath[i] + let node = this + for (let i = 0; i < internalPath.length && node; i++) { + const childIndex = internalPath[i] node = node.childs[childIndex] } @@ -206,10 +206,10 @@ Node.prototype.serialize = function () { * @return {Node | null} Returns the Node when found, returns null if not found */ Node.prototype.findNode = function (jsonPath) { - var path = util.parsePath(jsonPath) - var node = this + const path = util.parsePath(jsonPath) + let node = this while (node && path.length > 0) { - var prop = path.shift() + const prop = path.shift() if (typeof prop === 'number') { if (node.type !== 'array') { throw new Error('Cannot get child node at index ' + prop + ': node is no array') @@ -219,9 +219,7 @@ Node.prototype.findNode = function (jsonPath) { if (node.type !== 'object') { throw new Error('Cannot get child node ' + prop + ': node is no object') } - node = node.childs.filter(function (child) { - return child.field === prop - })[0] + node = node.childs.filter(child => child.field === prop)[0] } } @@ -234,8 +232,8 @@ Node.prototype.findNode = function (jsonPath) { * @return {Array.} */ Node.prototype.findParents = function () { - var parents = [] - var parent = this.parent + const parents = [] + let parent = this.parent while (parent) { parents.unshift(parent) parent = parent.parent @@ -264,8 +262,8 @@ Node.prototype.setError = function (error, child) { * Render the error */ Node.prototype.updateError = function () { - var error = this.fieldError || this.valueError || this.error - var tdError = this.dom.tdError + const error = this.fieldError || this.valueError || this.error + let tdError = this.dom.tdError if (error && this.dom && this.dom.tr) { util.addClassName(this.dom.tr, 'jsoneditor-validation-error') @@ -275,26 +273,26 @@ Node.prototype.updateError = function () { this.dom.tdValue.parentNode.appendChild(tdError) } - var popover = document.createElement('div') + const popover = document.createElement('div') popover.className = 'jsoneditor-popover jsoneditor-right' popover.appendChild(document.createTextNode(error.message)) - var button = document.createElement('button') + const button = document.createElement('button') button.type = 'button' button.className = 'jsoneditor-button jsoneditor-schema-error' button.appendChild(popover) // update the direction of the popover button.onmouseover = button.onfocus = function updateDirection () { - var directions = ['right', 'above', 'below', 'left'] - for (var i = 0; i < directions.length; i++) { - var direction = directions[i] + const directions = ['right', 'above', 'below', 'left'] + for (let i = 0; i < directions.length; i++) { + const direction = directions[i] popover.className = 'jsoneditor-popover jsoneditor-' + direction - var contentRect = this.editor.content.getBoundingClientRect() - var popoverRect = popover.getBoundingClientRect() - var margin = 20 // account for a scroll bar - var fit = util.insideRect(contentRect, popoverRect, margin) + const contentRect = this.editor.content.getBoundingClientRect() + const popoverRect = popover.getBoundingClientRect() + const margin = 20 // account for a scroll bar + const fit = util.insideRect(contentRect, popoverRect, margin) if (fit) { break @@ -304,14 +302,14 @@ Node.prototype.updateError = function () { // when clicking the error icon, expand all nodes towards the invalid // child node, and set focus to the child node - var child = this.errorChild + const child = this.errorChild if (child) { button.onclick = function showInvalidNode () { - child.findParents().forEach(function (parent) { + child.findParents().forEach(parent => { parent.expand(false) }) - child.scrollTo(function () { + child.scrollTo(() => { child.focus() }) } @@ -341,7 +339,7 @@ Node.prototype.updateError = function () { */ Node.prototype.getIndex = function () { if (this.parent) { - var index = this.parent.childs.indexOf(this) + const index = this.parent.childs.indexOf(this) return index !== -1 ? index : null } else { return -1 @@ -386,10 +384,10 @@ Node.prototype.getField = function () { * 'array', 'object', or 'string' */ Node.prototype.setValue = function (value, type) { - var childValue, child, visible - var i, j - var notUpdateDom = false - var previousChilds = this.childs + let childValue, child, visible + let i, j + const notUpdateDom = false + const previousChilds = this.childs this.type = this._getType(value) @@ -451,7 +449,7 @@ Node.prototype.setValue = function (value, type) { } i = 0 - for (var childField in value) { + for (const childField in value) { if (hasOwnProperty(value, childField)) { childValue = value[childField] if (childValue !== undefined && !(childValue instanceof Function)) { @@ -509,10 +507,10 @@ Node.prototype.setValue = function (value, type) { * order and duplicates in objects */ Node.prototype.setInternalValue = function (internalValue) { - var childValue, child, visible - var i, j - var notUpdateDom = false - var previousChilds = this.childs + let childValue, child, visible + let i, j + const notUpdateDom = false + const previousChilds = this.childs this.type = internalValue.type @@ -609,7 +607,7 @@ Node.prototype.setInternalValue = function (internalValue) { */ Node.prototype.recreateDom = function () { if (this.dom && this.dom.tr && this.dom.tr.parentNode) { - var domAnchor = this._detachFromDom() + const domAnchor = this._detachFromDom() this.clearDom() @@ -625,14 +623,14 @@ Node.prototype.recreateDom = function () { */ Node.prototype.getValue = function () { if (this.type === 'array') { - var arr = [] - this.childs.forEach(function (child) { + const arr = [] + this.childs.forEach(child => { arr.push(child.getValue()) }) return arr } else if (this.type === 'object') { - var obj = {} - this.childs.forEach(function (child) { + const obj = {} + this.childs.forEach(child => { obj[child.getField()] = child.getValue() }) return obj @@ -653,19 +651,15 @@ Node.prototype.getInternalValue = function () { if (this.type === 'array') { return { type: this.type, - childs: this.childs.map(function (child) { - return child.getInternalValue() - }) + childs: this.childs.map(child => child.getInternalValue()) } } else if (this.type === 'object') { return { type: this.type, - childs: this.childs.map(function (child) { - return { - field: child.getField(), - value: child.getInternalValue() - } - }) + childs: this.childs.map(child => ({ + field: child.getField(), + value: child.getInternalValue() + })) } } else { if (this.value === undefined) { @@ -692,7 +686,7 @@ Node.prototype.getLevel = function () { * @return {Node[]} Returns an array with nodes */ Node.prototype.getNodePath = function () { - var path = this.parent ? this.parent.getNodePath() : [] + const path = this.parent ? this.parent.getNodePath() : [] path.push(this) return path } @@ -704,7 +698,7 @@ Node.prototype.getNodePath = function () { * @return {Node} clone */ Node.prototype.clone = function () { - var clone = new Node(this.editor) + const clone = new Node(this.editor) clone.type = this.type clone.field = this.field clone.fieldInnerText = this.fieldInnerText @@ -718,9 +712,9 @@ Node.prototype.clone = function () { if (this.childs) { // an object or array - var cloneChilds = [] - this.childs.forEach(function (child) { - var childClone = child.clone() + const cloneChilds = [] + this.childs.forEach(child => { + const childClone = child.clone() childClone.setParent(clone) cloneChilds.push(childClone) }) @@ -752,7 +746,7 @@ Node.prototype.expand = function (recurse) { this.showChilds() if (recurse !== false) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.expand(recurse) }) } @@ -772,7 +766,7 @@ Node.prototype.collapse = function (recurse) { // collapse childs in case of recurse if (recurse !== false) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.collapse(recurse) }) } @@ -788,7 +782,7 @@ Node.prototype.collapse = function (recurse) { * Recursively show all childs when they are expanded */ Node.prototype.showChilds = function () { - var childs = this.childs + const childs = this.childs if (!childs) { return } @@ -796,12 +790,12 @@ Node.prototype.showChilds = function () { return } - var tr = this.dom.tr - var nextTr - var table = tr ? tr.parentNode : undefined + const tr = this.dom.tr + let nextTr + const table = tr ? tr.parentNode : undefined if (table) { // show row with append button - var append = this.getAppendDom() + const append = this.getAppendDom() if (!append.parentNode) { nextTr = tr.nextSibling if (nextTr) { @@ -812,10 +806,10 @@ Node.prototype.showChilds = function () { } // show childs - var iMax = Math.min(this.childs.length, this.visibleChilds) + const iMax = Math.min(this.childs.length, this.visibleChilds) nextTr = this._getNextTr() - for (var i = 0; i < iMax; i++) { - var child = this.childs[i] + for (let i = 0; i < iMax; i++) { + const child = this.childs[i] if (!child.getDom().parentNode) { table.insertBefore(child.getDom(), nextTr) } @@ -823,7 +817,7 @@ Node.prototype.showChilds = function () { } // show "show more childs" if limited - var showMore = this.getShowMoreDom() + const showMore = this.getShowMoreDom() nextTr = this._getNextTr() if (!showMore.parentNode) { table.insertBefore(showMore, nextTr) @@ -847,8 +841,8 @@ Node.prototype._getNextTr = function () { * @param {{resetVisibleChilds: boolean}} [options] */ Node.prototype.hide = function (options) { - var tr = this.dom.tr - var table = tr ? tr.parentNode : undefined + const tr = this.dom.tr + const table = tr ? tr.parentNode : undefined if (table) { table.removeChild(tr) } @@ -860,7 +854,7 @@ Node.prototype.hide = function (options) { * @param {{resetVisibleChilds: boolean}} [options] */ Node.prototype.hideChilds = function (options) { - var childs = this.childs + const childs = this.childs if (!childs) { return } @@ -869,18 +863,18 @@ Node.prototype.hideChilds = function (options) { } // hide append row - var append = this.getAppendDom() + const append = this.getAppendDom() if (append.parentNode) { append.parentNode.removeChild(append) } // hide childs - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.hide() }) // hide "show more" row - var showMore = this.getShowMoreDom() + const showMore = this.getShowMoreDom() if (showMore.parentNode) { showMore.parentNode.removeChild(showMore) } @@ -901,7 +895,7 @@ Node.prototype._updateCssClassName = function () { typeof this.editor.options.onClassName === 'function' && this.dom.tree) { util.removeAllClassNames(this.dom.tree) - var addClasses = this.editor.options.onClassName({ path: this.getPath(), field: this.field, value: this.value }) || '' + const addClasses = this.editor.options.onClassName({ path: this.getPath(), field: this.field, value: this.value }) || '' util.addClassName(this.dom.tree, 'jsoneditor-values ' + addClasses) } } @@ -909,7 +903,7 @@ Node.prototype._updateCssClassName = function () { Node.prototype.recursivelyUpdateCssClassesOnNodes = function () { this._updateCssClassName() if (Array.isArray(this.childs)) { - for (var i = 0; i < this.childs.length; i++) { + for (let i = 0; i < this.childs.length; i++) { this.childs[i].recursivelyUpdateCssClassesOnNodes() } } @@ -919,7 +913,7 @@ Node.prototype.recursivelyUpdateCssClassesOnNodes = function () { * Goes through the path from the node to the root and ensures that it is expanded */ Node.prototype.expandTo = function () { - var currentNode = this.parent + let currentNode = this.parent while (currentNode) { if (!currentNode.expanded) { currentNode.expand() @@ -953,9 +947,9 @@ Node.prototype.appendChild = function (node, visible, updateDom) { if (this.expanded && visible !== false) { // insert into the DOM, before the appendRow - var newTr = node.getDom() - var nextTr = this._getNextTr() - var table = nextTr ? nextTr.parentNode : undefined + const newTr = node.getDom() + const nextTr = this._getNextTr() + const table = nextTr ? nextTr.parentNode : undefined if (nextTr && table) { table.insertBefore(newTr, nextTr) } @@ -982,7 +976,7 @@ Node.prototype.moveBefore = function (node, beforeNode) { if (this._hasChilds()) { // create a temporary row, to prevent the scroll position from jumping // when removing the node - var tbody = (this.dom.tr) ? this.dom.tr.parentNode : undefined + const tbody = (this.dom.tr) ? this.dom.tr.parentNode : undefined if (tbody) { var trTemp = document.createElement('tr') trTemp.style.height = tbody.clientHeight + 'px' @@ -996,7 +990,7 @@ Node.prototype.moveBefore = function (node, beforeNode) { if (beforeNode instanceof AppendNode || !beforeNode) { // the this.childs.length + 1 is to reckon with the node that we're about to add if (this.childs.length + 1 > this.visibleChilds) { - var lastVisibleNode = this.childs[this.visibleChilds - 1] + const lastVisibleNode = this.childs[this.visibleChilds - 1] this.insertBefore(node, lastVisibleNode) } else { this.appendChild(node) @@ -1035,7 +1029,7 @@ Node.prototype.insertBefore = function (node, beforeNode) { this.childs.push(node) } else { // insert before a child node - var index = this.childs.indexOf(beforeNode) + const index = this.childs.indexOf(beforeNode) if (index === -1) { throw new Error('Node not found') } @@ -1048,9 +1042,9 @@ Node.prototype.insertBefore = function (node, beforeNode) { if (this.expanded) { // insert into the DOM - var newTr = node.getDom() - var nextTr = beforeNode.getDom() - var table = nextTr ? nextTr.parentNode : undefined + const newTr = node.getDom() + const nextTr = beforeNode.getDom() + const table = nextTr ? nextTr.parentNode : undefined if (nextTr && table) { table.insertBefore(newTr, nextTr) } @@ -1072,8 +1066,8 @@ Node.prototype.insertBefore = function (node, beforeNode) { */ Node.prototype.insertAfter = function (node, afterNode) { if (this._hasChilds()) { - var index = this.childs.indexOf(afterNode) - var beforeNode = this.childs[index + 1] + const index = this.childs.indexOf(afterNode) + const beforeNode = this.childs[index + 1] if (beforeNode) { this.insertBefore(node, beforeNode) } else { @@ -1094,8 +1088,8 @@ Node.prototype.search = function (text, results) { if (!Array.isArray(results)) { results = [] } - var index - var search = text ? text.toLowerCase() : undefined + let index + const search = text ? text.toLowerCase() : undefined // delete old search data delete this.searchField @@ -1103,7 +1097,7 @@ Node.prototype.search = function (text, results) { // search in field if (this.field !== undefined && results.length <= this.MAX_SEARCH_RESULTS) { - var field = String(this.field).toLowerCase() + const field = String(this.field).toLowerCase() index = field.indexOf(search) if (index !== -1) { this.searchField = true @@ -1123,14 +1117,14 @@ Node.prototype.search = function (text, results) { // search the nodes childs if (this.childs) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.search(text, results) }) } } else { // string, auto if (this.value !== undefined && results.length <= this.MAX_SEARCH_RESULTS) { - var value = String(this.value).toLowerCase() + const value = String(this.value).toLowerCase() index = value.indexOf(search) if (index !== -1) { this.searchValue = true @@ -1165,11 +1159,11 @@ Node.prototype.scrollTo = function (callback) { * if the node is not visible, expand its parents */ Node.prototype.expandPathToNode = function () { - var node = this - var recurse = false + let node = this + const recurse = false while (node && node.parent) { // expand visible childs of the parent if needed - var index = node.parent.type === 'array' + const index = node.parent.type === 'array' ? node.index : node.parent.childs.indexOf(node) while (node.parent.visibleChilds < index + 1) { @@ -1195,7 +1189,7 @@ Node.prototype.focus = function (elementName) { Node.focusElement = elementName if (this.dom.tr && this.dom.tr.parentNode) { - var dom = this.dom + const dom = this.dom switch (elementName) { case 'drag': @@ -1263,8 +1257,8 @@ Node.prototype.focus = function (elementName) { * Select all text in an editable div after a delay of 0 ms * @param {Element} editableDiv */ -Node.select = function (editableDiv) { - setTimeout(function () { +Node.select = editableDiv => { + setTimeout(() => { util.selectContentEditable(editableDiv) }, 0) } @@ -1280,10 +1274,10 @@ Node.prototype.containsNode = function (node) { return true } - var childs = this.childs + const childs = this.childs if (childs) { // TODO: use the js5 Array.some() here? - for (var i = 0, iMax = childs.length; i < iMax; i++) { + for (let i = 0, iMax = childs.length; i < iMax; i++) { if (childs[i].containsNode(node)) { return true } @@ -1304,7 +1298,7 @@ Node.prototype.containsNode = function (node) { */ Node.prototype.removeChild = function (node, updateDom) { if (this.childs) { - var index = this.childs.indexOf(node) + const index = this.childs.indexOf(node) if (index !== -1) { if (index < this.visibleChilds && this.expanded) { @@ -1317,7 +1311,7 @@ Node.prototype.removeChild = function (node, updateDom) { delete node.searchField delete node.searchValue - var removedNode = this.childs.splice(index, 1)[0] + const removedNode = this.childs.splice(index, 1)[0] removedNode.parent = null if (updateDom !== false) { @@ -1347,7 +1341,7 @@ Node.prototype._remove = function (node) { * @param {String} newType */ Node.prototype.changeType = function (newType) { - var oldType = this.type + const oldType = this.type if (oldType === newType) { // type is not changed @@ -1360,7 +1354,7 @@ Node.prototype.changeType = function (newType) { this.type = newType } else { // change from array to object, or from string/auto to object/array - var domAnchor = this._detachFromDom() + const domAnchor = this._detachFromDom() // delete the old DOM this.clearDom() @@ -1374,7 +1368,7 @@ Node.prototype.changeType = function (newType) { this.childs = [] } - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.clearDom() delete child.index child.fieldEditable = true @@ -1391,7 +1385,7 @@ Node.prototype.changeType = function (newType) { this.childs = [] } - this.childs.forEach(function (child, index) { + this.childs.forEach((child, index) => { child.clearDom() child.fieldEditable = false child.index = index @@ -1426,7 +1420,7 @@ Node.prototype.changeType = function (newType) { * @param {*} json */ Node.prototype.deepEqual = function (json) { - var i + let i if (this.type === 'array') { if (!Array.isArray(json)) { @@ -1449,10 +1443,10 @@ Node.prototype.deepEqual = function (json) { // TODO: for better efficiency, we could create a property `isDuplicate` on all of the childs // and keep that up to date. This should make deepEqual about 20% faster. - var props = {} - var propCount = 0 + const props = {} + let propCount = 0 for (i = 0; i < this.childs.length; i++) { - var child = this.childs[i] + const child = this.childs[i] if (!props[child.field]) { // We can have childs with duplicate field names. // We take the first, and ignore the others. @@ -1495,11 +1489,11 @@ Node.prototype._getDomValue = function () { if (this.valueInnerText !== undefined) { try { // retrieve the value - var value + let value if (this.type === 'string') { value = this._unescapeHTML(this.valueInnerText) } else { - var str = this._unescapeHTML(this.valueInnerText) + const str = this._unescapeHTML(this.valueInnerText) value = util.parseString(str) } if (value !== this.value) { @@ -1558,15 +1552,15 @@ Node.prototype._clearFieldError = function () { Node.prototype._onChangeValue = function () { // get current selection, then override the range such that we can select // the added/removed text on undo/redo - var oldSelection = this.editor.getDomSelection() + const oldSelection = this.editor.getDomSelection() if (oldSelection.range) { - var undoDiff = util.textDiff(String(this.value), String(this.previousValue)) + const undoDiff = util.textDiff(String(this.value), String(this.previousValue)) oldSelection.range.startOffset = undoDiff.start oldSelection.range.endOffset = undoDiff.end } - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() if (newSelection.range) { - var redoDiff = util.textDiff(String(this.previousValue), String(this.value)) + const redoDiff = util.textDiff(String(this.previousValue), String(this.value)) newSelection.range.startOffset = redoDiff.start newSelection.range.endOffset = redoDiff.end } @@ -1589,16 +1583,16 @@ Node.prototype._onChangeValue = function () { Node.prototype._onChangeField = function () { // get current selection, then override the range such that we can select // the added/removed text on undo/redo - var oldSelection = this.editor.getDomSelection() - var previous = this.previousField || '' + const oldSelection = this.editor.getDomSelection() + const previous = this.previousField || '' if (oldSelection.range) { - var undoDiff = util.textDiff(this.field, previous) + const undoDiff = util.textDiff(this.field, previous) oldSelection.range.startOffset = undoDiff.start oldSelection.range.endOffset = undoDiff.end } - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() if (newSelection.range) { - var redoDiff = util.textDiff(previous, this.field) + const redoDiff = util.textDiff(previous, this.field) newSelection.range.startOffset = redoDiff.start newSelection.range.endOffset = redoDiff.end } @@ -1623,21 +1617,21 @@ Node.prototype._onChangeField = function () { * @private */ Node.prototype._updateDomValue = function () { - var domValue = this.dom.value + const domValue = this.dom.value if (domValue) { - var classNames = ['jsoneditor-value'] + const classNames = ['jsoneditor-value'] // set text color depending on value type - var value = this.value - var type = (this.type === 'auto') ? util.type(value) : this.type - var isUrl = type === 'string' && util.isUrl(value) + const value = this.value + const type = (this.type === 'auto') ? util.type(value) : this.type + const isUrl = type === 'string' && util.isUrl(value) classNames.push('jsoneditor-' + type) if (isUrl) { classNames.push('jsoneditor-url') } // visual styling when empty - var isEmpty = (String(this.value) === '' && this.type !== 'array' && this.type !== 'object') + const isEmpty = (String(this.value) === '' && this.type !== 'array' && this.type !== 'object') if (isEmpty) { classNames.push('jsoneditor-empty') } @@ -1654,7 +1648,7 @@ Node.prototype._updateDomValue = function () { // update title if (type === 'array' || type === 'object') { - var count = this.childs ? this.childs.length : 0 + const count = this.childs ? this.childs.length : 0 domValue.title = this.type + ' containing ' + count + ' items' } else if (isUrl && this.editable.value) { domValue.title = translate('openUrl') @@ -1699,7 +1693,7 @@ Node.prototype._updateDomValue = function () { this.dom.select.appendChild(this.dom.select.option) // Iterate all enum values and add them as options - for (var i = 0; i < this.enum.length; i++) { + for (let i = 0; i < this.enum.length; i++) { this.dom.select.option = document.createElement('option') this.dom.select.option.value = this.enum[i] this.dom.select.option.innerHTML = this.enum[i] @@ -1812,15 +1806,15 @@ Node.prototype._deleteDomColor = function () { * @private */ Node.prototype._updateDomField = function () { - var domField = this.dom.field + const domField = this.dom.field if (domField) { - var tooltip = util.makeFieldTooltip(this.schema, this.editor.options.language) + const tooltip = util.makeFieldTooltip(this.schema, this.editor.options.language) if (tooltip) { domField.title = tooltip } // make backgound color lightgray when empty - var isEmpty = (String(this.field) === '' && this.parent.type !== 'array') + const isEmpty = (String(this.field) === '' && this.parent.type !== 'array') if (isEmpty) { util.addClassName(domField, 'jsoneditor-empty') } else { @@ -1859,10 +1853,10 @@ Node.prototype._getDomField = function (forceUnique) { if (this.fieldInnerText !== undefined) { try { - var field = this._unescapeHTML(this.fieldInnerText) + let field = this._unescapeHTML(this.fieldInnerText) - var existingFieldNames = this.parent.getFieldNames(this) - var isDuplicate = existingFieldNames.indexOf(field) !== -1 + const existingFieldNames = this.parent.getFieldNames(this) + const isDuplicate = existingFieldNames.indexOf(field) !== -1 if (!isDuplicate) { if (field !== this.field) { @@ -1902,7 +1896,7 @@ Node.prototype._updateDomDefault = function () { } // select either enum dropdown (select) or input value - var inputElement = this.dom.select + const inputElement = this.dom.select ? this.dom.select : this.dom.value @@ -1938,7 +1932,7 @@ Node.prototype.clearDom = function () { * @return {Element} tr HTML DOM TR Element */ Node.prototype.getDom = function () { - var dom = this.dom + const dom = this.dom if (dom.tr) { return dom.tr } @@ -1950,11 +1944,11 @@ Node.prototype.getDom = function () { dom.tr.node = this if (this.editor.options.mode === 'tree') { // note: we take here the global setting - var tdDrag = document.createElement('td') + const tdDrag = document.createElement('td') if (this.editable.field) { // create draggable area if (this.parent) { - var domDrag = document.createElement('button') + const domDrag = document.createElement('button') domDrag.type = 'button' dom.drag = domDrag domDrag.className = 'jsoneditor-button jsoneditor-dragarea' @@ -1965,8 +1959,8 @@ Node.prototype.getDom = function () { dom.tr.appendChild(tdDrag) // create context menu - var tdMenu = document.createElement('td') - var menu = document.createElement('button') + const tdMenu = document.createElement('td') + const menu = document.createElement('button') menu.type = 'button' dom.menu = menu menu.className = 'jsoneditor-button jsoneditor-contextmenu' @@ -1976,7 +1970,7 @@ Node.prototype.getDom = function () { } // create tree and field - var tdField = document.createElement('td') + const tdField = document.createElement('td') dom.tr.appendChild(tdField) dom.tree = this._createDomTree() tdField.appendChild(dom.tree) @@ -1999,7 +1993,7 @@ Node.prototype.isVisible = function () { * @param {Node[] | Node} nodes * @param {Event} event */ -Node.onDragStart = function (nodes, event) { +Node.onDragStart = (nodes, event) => { if (!Array.isArray(nodes)) { return Node.onDragStart([nodes], event) } @@ -2007,24 +2001,24 @@ Node.onDragStart = function (nodes, event) { return } - var firstNode = nodes[0] - var lastNode = nodes[nodes.length - 1] - var parent = firstNode.parent - var draggedNode = Node.getNodeFromTarget(event.target) - var editor = firstNode.editor + const firstNode = nodes[0] + const lastNode = nodes[nodes.length - 1] + const parent = firstNode.parent + const draggedNode = Node.getNodeFromTarget(event.target) + const editor = firstNode.editor // in case of multiple selected nodes, offsetY prevents the selection from // jumping when you start dragging one of the lower down nodes in the selection - var offsetY = util.getAbsoluteTop(draggedNode.dom.tr) - util.getAbsoluteTop(firstNode.dom.tr) + const offsetY = util.getAbsoluteTop(draggedNode.dom.tr) - util.getAbsoluteTop(firstNode.dom.tr) if (!editor.mousemove) { - editor.mousemove = util.addEventListener(window, 'mousemove', function (event) { + editor.mousemove = util.addEventListener(window, 'mousemove', event => { Node.onDrag(nodes, event) }) } if (!editor.mouseup) { - editor.mouseup = util.addEventListener(window, 'mouseup', function (event) { + editor.mouseup = util.addEventListener(window, 'mouseup', event => { Node.onDragEnd(nodes, event) }) } @@ -2052,7 +2046,7 @@ Node.onDragStart = function (nodes, event) { * @param {Node[] | Node} nodes * @param {Event} event */ -Node.onDrag = function (nodes, event) { +Node.onDrag = (nodes, event) => { if (!Array.isArray(nodes)) { return Node.onDrag([nodes], event) } @@ -2061,21 +2055,21 @@ Node.onDrag = function (nodes, event) { } // TODO: this method has grown too large. Split it in a number of methods - var editor = nodes[0].editor - var mouseY = event.pageY - editor.drag.offsetY - var mouseX = event.pageX - var trThis, trPrev, trNext, trFirst, trLast, trRoot - var nodePrev, nodeNext - var topThis, topPrev, topFirst, heightThis, bottomNext, heightNext - var moved = false + const editor = nodes[0].editor + const mouseY = event.pageY - editor.drag.offsetY + const mouseX = event.pageX + let trPrev, trNext, trFirst, trLast, trRoot + let nodePrev, nodeNext + let topPrev, topFirst, bottomNext, heightNext + let moved = false // TODO: add an ESC option, which resets to the original position // move up/down - var firstNode = nodes[0] - trThis = firstNode.dom.tr - topThis = util.getAbsoluteTop(trThis) - heightThis = trThis.offsetHeight + const firstNode = nodes[0] + const trThis = firstNode.dom.tr + let topThis = util.getAbsoluteTop(trThis) + const heightThis = trThis.offsetHeight if (mouseY < topThis) { // move up trPrev = trThis @@ -2110,14 +2104,14 @@ Node.onDrag = function (nodes, event) { } if (nodePrev) { - nodes.forEach(function (node) { + nodes.forEach(node => { nodePrev.parent.moveBefore(node, nodePrev) }) moved = true } } else { // move down - var lastNode = nodes[nodes.length - 1] + const lastNode = nodes[nodes.length - 1] trLast = (lastNode.expanded && lastNode.append) ? lastNode.append.getDom() : lastNode.dom.tr trFirst = trLast ? trLast.nextSibling : undefined if (trFirst) { @@ -2146,24 +2140,22 @@ Node.onDrag = function (nodes, event) { if (nodeNext && nodeNext.parent) { // calculate the desired level - var diffX = (mouseX - editor.drag.mouseX) - var diffLevel = Math.round(diffX / 24 / 2) - var level = editor.drag.level + diffLevel // desired level - var levelNext = nodeNext.getLevel() // level to be + const diffX = (mouseX - editor.drag.mouseX) + const diffLevel = Math.round(diffX / 24 / 2) + const level = editor.drag.level + diffLevel // desired level + let levelNext = nodeNext.getLevel() // level to be // find the best fitting level (move upwards over the append nodes) trPrev = nodeNext.dom.tr && nodeNext.dom.tr.previousSibling while (levelNext < level && trPrev) { nodePrev = Node.getNodeFromTarget(trPrev) - var isDraggedNode = nodes.some(function (node) { - return node === nodePrev || nodePrev.isDescendantOf(node) - }) + const isDraggedNode = nodes.some(node => node === nodePrev || nodePrev.isDescendantOf(node)) if (isDraggedNode) { // neglect the dragged nodes themselves and their childs } else if (nodePrev instanceof AppendNode) { - var childs = nodePrev.parent.childs + const childs = nodePrev.parent.childs if (childs.length !== nodes.length || childs[nodes.length - 1] !== lastNode) { // non-visible append node of a list of childs // consisting of not only this node (else the @@ -2188,7 +2180,7 @@ Node.onDrag = function (nodes, event) { // move the node when its position is changed if (nodeNext && nodeNext.dom.tr && trLast.nextSibling !== nodeNext.dom.tr) { - nodes.forEach(function (node) { + nodes.forEach(node => { nodeNext.parent.moveBefore(node, nodeNext) }) moved = true @@ -2214,7 +2206,7 @@ Node.onDrag = function (nodes, event) { * @param {Node[] | Node} nodes * @param {Event} event */ -Node.onDragEnd = function (nodes, event) { +Node.onDragEnd = (nodes, event) => { if (!Array.isArray(nodes)) { return Node.onDrag([nodes], event) } @@ -2222,23 +2214,23 @@ Node.onDragEnd = function (nodes, event) { return } - var firstNode = nodes[0] - var editor = firstNode.editor + const firstNode = nodes[0] + const editor = firstNode.editor // set focus to the context menu button of the first node if (nodes[0]) { nodes[0].dom.menu.focus() } - var oldParentPath = editor.drag.oldParent.getInternalPath() - var newParentPath = firstNode.parent.getInternalPath() - var sameParent = editor.drag.oldParent === firstNode.parent - var oldIndex = editor.drag.oldNextNode.getIndex() - var newIndex = firstNode.getIndex() - var oldParentPathRedo = editor.drag.oldParentPathRedo + const oldParentPath = editor.drag.oldParent.getInternalPath() + const newParentPath = firstNode.parent.getInternalPath() + const sameParent = editor.drag.oldParent === firstNode.parent + const oldIndex = editor.drag.oldNextNode.getIndex() + const newIndex = firstNode.getIndex() + const oldParentPathRedo = editor.drag.oldParentPathRedo - var oldIndexRedo = editor.drag.oldIndexRedo - var newIndexRedo = (sameParent && oldIndexRedo < newIndex) + const oldIndexRedo = editor.drag.oldIndexRedo + const newIndexRedo = (sameParent && oldIndexRedo < newIndex) ? (newIndex + nodes.length) : newIndex @@ -2265,7 +2257,7 @@ Node.onDragEnd = function (nodes, event) { document.body.style.cursor = editor.drag.oldCursor editor.highlighter.unlock() - nodes.forEach(function (node) { + nodes.forEach(node => { node.updateDom() if (event.target !== node.dom.drag && event.target !== node.dom.menu) { @@ -2296,7 +2288,7 @@ Node.onDragEnd = function (nodes, event) { * @private */ Node.prototype.isDescendantOf = function (node) { - var n = this.parent + let n = this.parent while (n) { if (n === node) { return true @@ -2312,9 +2304,7 @@ Node.prototype.isDescendantOf = function (node) { * @return {Element} domField * @private */ -Node.prototype._createDomField = function () { - return document.createElement('div') -} +Node.prototype._createDomField = () => document.createElement('div') /** * Set highlighting for this node and all its childs. @@ -2334,7 +2324,7 @@ Node.prototype.setHighlight = function (highlight) { } if (this.childs) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.setHighlight(highlight) }) } @@ -2371,7 +2361,7 @@ Node.prototype.setSelected = function (selected, isFirst) { } if (this.childs) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.setSelected(selected) }) } @@ -2413,13 +2403,13 @@ Node.prototype.updateField = function (field) { */ Node.prototype.updateDom = function (options) { // update level indentation - var domTree = this.dom.tree + const domTree = this.dom.tree if (domTree) { domTree.style.marginLeft = this.getLevel() * 24 + 'px' } // apply field to DOM - var domField = this.dom.field + const domField = this.dom.field if (domField) { if (this.fieldEditable) { // parent is an object @@ -2432,13 +2422,13 @@ Node.prototype.updateDom = function (options) { domField.className = 'jsoneditor-readonly' } - var fieldText + let fieldText if (this.index !== undefined) { fieldText = this.index } else if (this.field !== undefined) { fieldText = this.field } else { - var schema = this.editor.options.schema + const schema = this.editor.options.schema ? Node._findSchema(this.editor.options.schema, this.editor.options.schemaRefs || {}, this.getPath()) : undefined @@ -2456,7 +2446,7 @@ Node.prototype.updateDom = function (options) { } // apply value to DOM - var domValue = this.dom.value + const domValue = this.dom.value if (domValue) { if (this.type === 'array') { this.updateNodeName() @@ -2485,7 +2475,7 @@ Node.prototype.updateDom = function (options) { // update childs recursively if (options && options.recurse === true) { if (this.childs) { - this.childs.forEach(function (child) { + this.childs.forEach(child => { child.updateDom(options) }) } @@ -2534,14 +2524,14 @@ Node.prototype._updateSchema = function () { * @return {Array | null} Returns the enum when found, null otherwise. * @private */ -Node._findEnum = function (schema) { +Node._findEnum = schema => { if (schema.enum) { return schema.enum } - var composite = schema.oneOf || schema.anyOf || schema.allOf + const composite = schema.oneOf || schema.anyOf || schema.allOf if (composite) { - var match = composite.filter(function (entry) { return entry.enum }) + const match = composite.filter(entry => entry.enum) if (match.length > 0) { return match[0].enum } @@ -2558,16 +2548,16 @@ Node._findEnum = function (schema) { * @return {Object | null} * @private */ -Node._findSchema = function (schema, schemaRefs, path) { - var childSchema = schema - var foundSchema = childSchema +Node._findSchema = (schema, schemaRefs, path) => { + let childSchema = schema + let foundSchema = childSchema - var allSchemas = schema.oneOf || schema.anyOf || schema.allOf + let allSchemas = schema.oneOf || schema.anyOf || schema.allOf if (!allSchemas) { allSchemas = [schema] } - for (var j = 0; j < allSchemas.length; j++) { + for (let j = 0; j < allSchemas.length; j++) { childSchema = allSchemas[j] if ('$ref' in childSchema && typeof childSchema.$ref === 'string') { @@ -2577,12 +2567,12 @@ Node._findSchema = function (schema, schemaRefs, path) { } } - for (var i = 0; i < path.length && childSchema; i++) { - var nextPath = path.slice(i + 1, path.length) - var key = path[i] + for (let i = 0; i < path.length && childSchema; i++) { + const nextPath = path.slice(i + 1, path.length) + const key = path[i] if (typeof key === 'string' && childSchema.patternProperties && !(childSchema.properties && key in childSchema.properties)) { - for (var prop in childSchema.patternProperties) { + for (const prop in childSchema.patternProperties) { if (key.match(prop)) { foundSchema = Node._findSchema(childSchema.patternProperties[prop], schemaRefs, nextPath) } @@ -2620,19 +2610,19 @@ Node._findSchema = function (schema, schemaRefs, path) { * @private */ Node.prototype._updateDomIndexes = function () { - var domValue = this.dom.value - var childs = this.childs + const domValue = this.dom.value + const childs = this.childs if (domValue && childs) { if (this.type === 'array') { - childs.forEach(function (child, index) { + childs.forEach((child, index) => { child.index = index - var childField = child.dom.field + const childField = child.dom.field if (childField) { childField.innerHTML = index } }) } else if (this.type === 'object') { - childs.forEach(function (child) { + childs.forEach(child => { if (child.index !== undefined) { delete child.index @@ -2650,7 +2640,7 @@ Node.prototype._updateDomIndexes = function () { * @private */ Node.prototype._createDomValue = function () { - var domValue + let domValue if (this.type === 'array') { domValue = document.createElement('div') @@ -2683,7 +2673,7 @@ Node.prototype._createDomValue = function () { */ Node.prototype._createDomExpandButton = function () { // create expand button - var expand = document.createElement('button') + const expand = document.createElement('button') expand.type = 'button' if (this._hasChilds()) { expand.className = this.expanded @@ -2704,17 +2694,17 @@ Node.prototype._createDomExpandButton = function () { * @private */ Node.prototype._createDomTree = function () { - var dom = this.dom - var domTree = document.createElement('table') - var tbody = document.createElement('tbody') + const dom = this.dom + const domTree = document.createElement('table') + const tbody = document.createElement('tbody') domTree.style.borderCollapse = 'collapse' // TODO: put in css domTree.className = 'jsoneditor-values' domTree.appendChild(tbody) - var tr = document.createElement('tr') + const tr = document.createElement('tr') tbody.appendChild(tr) // create expand button - var tdExpand = document.createElement('td') + const tdExpand = document.createElement('td') tdExpand.className = 'jsoneditor-tree' tr.appendChild(tdExpand) dom.expand = this._createDomExpandButton() @@ -2722,7 +2712,7 @@ Node.prototype._createDomTree = function () { dom.tdExpand = tdExpand // create the field - var tdField = document.createElement('td') + const tdField = document.createElement('td') tdField.className = 'jsoneditor-tree' tr.appendChild(tdField) dom.field = this._createDomField() @@ -2730,7 +2720,7 @@ Node.prototype._createDomTree = function () { dom.tdField = tdField // create a separator - var tdSeparator = document.createElement('td') + const tdSeparator = document.createElement('td') tdSeparator.className = 'jsoneditor-tree' tr.appendChild(tdSeparator) if (this.type !== 'object' && this.type !== 'array') { @@ -2740,7 +2730,7 @@ Node.prototype._createDomTree = function () { dom.tdSeparator = tdSeparator // create the value - var tdValue = document.createElement('td') + const tdValue = document.createElement('td') tdValue.className = 'jsoneditor-tree' tr.appendChild(tdValue) dom.value = this._createDomValue() @@ -2755,11 +2745,11 @@ Node.prototype._createDomTree = function () { * @param {Event} event */ Node.prototype.onEvent = function (event) { - var type = event.type - var target = event.target || event.srcElement - var dom = this.dom - var node = this - var expandable = this._hasChilds() + const type = event.type + const target = event.target || event.srcElement + const dom = this.dom + const node = this + const expandable = this._hasChilds() if (typeof this.editor.options.onEvent === 'function') { this._onEvent(event) @@ -2777,11 +2767,11 @@ Node.prototype.onEvent = function (event) { // context menu events if (type === 'click' && target === dom.menu) { - var highlighter = node.editor.highlighter + const highlighter = node.editor.highlighter highlighter.highlight(node) highlighter.lock() util.addClassName(dom.menu, 'jsoneditor-selected') - this.showContextMenu(dom.menu, function () { + this.showContextMenu(dom.menu, () => { util.removeClassName(dom.menu, 'jsoneditor-selected') highlighter.unlock() highlighter.unhighlight() @@ -2793,7 +2783,7 @@ Node.prototype.onEvent = function (event) { if (target === dom.expand || ((node.editor.options.mode === 'view' || node.editor.options.mode === 'form') && target.nodeName === 'DIV')) { if (expandable) { - var recurse = event.ctrlKey // with ctrl-key, expand/collapse all + const recurse = event.ctrlKey // with ctrl-key, expand/collapse all this._onExpand(recurse) } } @@ -2818,7 +2808,7 @@ Node.prototype.onEvent = function (event) { } // value events - var domValue = dom.value + const domValue = dom.value if (target === domValue) { // noinspection FallthroughInSwitchStatementJS switch (type) { @@ -2862,7 +2852,7 @@ Node.prototype.onEvent = function (event) { case 'cut': case 'paste': - setTimeout(function () { + setTimeout(() => { node._getDomValue() node._updateDomValue() }, 1) @@ -2871,7 +2861,7 @@ Node.prototype.onEvent = function (event) { } // field events - var domField = dom.field + const domField = dom.field if (target === domField) { switch (type) { case 'blur': @@ -2901,7 +2891,7 @@ Node.prototype.onEvent = function (event) { case 'cut': case 'paste': - setTimeout(function () { + setTimeout(() => { node._getDomField() node._updateDomField() }, 1) @@ -2911,9 +2901,9 @@ Node.prototype.onEvent = function (event) { // focus // when clicked in whitespace left or right from the field or value, set focus - var domTree = dom.tree + const domTree = dom.tree if (domTree && target === domTree.parentNode && type === 'click' && !event.hasMoved) { - var left = (event.offsetX !== undefined) + const left = (event.offsetX !== undefined) ? (event.offsetX < (this.getLevel() + 1) * 24) : (event.pageX < util.getAbsoluteLeft(dom.tdSeparator))// for FF if (left || expandable) { @@ -2952,9 +2942,9 @@ Node.prototype.onEvent = function (event) { * @private */ Node.prototype._onEvent = function (event) { - var element = event.target + const element = event.target if (element === this.dom.field || element === this.dom.value) { - var info = { + const info = { field: this.getField(), path: this.getPath() } @@ -2971,28 +2961,28 @@ Node.prototype._onEvent = function (event) { * @param {Event} event */ Node.prototype.onKeyDown = function (event) { - var keynum = event.which || event.keyCode - var target = event.target || event.srcElement - var ctrlKey = event.ctrlKey - var shiftKey = event.shiftKey - var altKey = event.altKey - var handled = false - var prevNode, nextNode, nextDom, nextDom2 - var editable = this.editor.options.mode === 'tree' - var oldSelection - var oldNextNode - var oldParent - var oldIndexRedo - var newIndexRedo - var oldParentPathRedo - var newParentPathRedo - var nodes - var multiselection - var selectedNodes = this.editor.multiselection.nodes.length > 0 + const keynum = event.which || event.keyCode + const target = event.target || event.srcElement + const ctrlKey = event.ctrlKey + const shiftKey = event.shiftKey + const altKey = event.altKey + let handled = false + let prevNode, nextNode, nextDom, nextDom2 + const editable = this.editor.options.mode === 'tree' + let oldSelection + let oldNextNode + let oldParent + let oldIndexRedo + let newIndexRedo + let oldParentPathRedo + let newParentPathRedo + let nodes + let multiselection + const selectedNodes = this.editor.multiselection.nodes.length > 0 ? this.editor.multiselection.nodes : [this] - var firstNode = selectedNodes[0] - var lastNode = selectedNodes[selectedNodes.length - 1] + const firstNode = selectedNodes[0] + const lastNode = selectedNodes[selectedNodes.length - 1] // console.log(ctrlKey, keynum, event.charCode); // TODO: cleanup if (keynum === 13) { // Enter @@ -3004,9 +2994,9 @@ Node.prototype.onKeyDown = function (event) { } } } else if (target === this.dom.expand) { - var expandable = this._hasChilds() + const expandable = this._hasChilds() if (expandable) { - var recurse = event.ctrlKey // with ctrl-key, expand/collapse all + const recurse = event.ctrlKey // with ctrl-key, expand/collapse all this._onExpand(recurse) target.focus() handled = true @@ -3044,7 +3034,7 @@ Node.prototype.onKeyDown = function (event) { } else if (keynum === 35) { // End if (altKey) { // Alt+End // find the last node - var endNode = this._lastNode() + const endNode = this._lastNode() if (endNode) { endNode.focus(Node.focusElement || this._getElementName(target)) } @@ -3053,7 +3043,7 @@ Node.prototype.onKeyDown = function (event) { } else if (keynum === 36) { // Home if (altKey) { // Alt+Home // find the first node - var homeNode = this._firstNode() + const homeNode = this._firstNode() if (homeNode) { homeNode.focus(Node.focusElement || this._getElementName(target)) } @@ -3062,14 +3052,14 @@ Node.prototype.onKeyDown = function (event) { } else if (keynum === 37) { // Arrow Left if (altKey && !shiftKey) { // Alt + Arrow Left // move to left element - var prevElement = this._previousElement(target) + const prevElement = this._previousElement(target) if (prevElement) { this.focus(this._getElementName(prevElement)) } handled = true } else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow left if (lastNode.expanded) { - var appendDom = lastNode.getAppendDom() + const appendDom = lastNode.getAppendDom() nextDom = appendDom ? appendDom.nextSibling : undefined } else { var dom = lastNode.getDom() @@ -3090,7 +3080,7 @@ Node.prototype.onKeyDown = function (event) { oldParentPathRedo = oldParent.getInternalPath() newParentPathRedo = nextNode2.parent.getInternalPath() - selectedNodes.forEach(function (node) { + selectedNodes.forEach(node => { nextNode2.parent.moveBefore(node, nextNode2) }) this.focus(Node.focusElement || this._getElementName(target)) @@ -3149,7 +3139,7 @@ Node.prototype.onKeyDown = function (event) { oldParentPathRedo = oldParent.getInternalPath() newParentPathRedo = prevNode.parent.getInternalPath() - selectedNodes.forEach(function (node) { + selectedNodes.forEach(node => { prevNode.parent.moveBefore(node, prevNode) }) this.focus(Node.focusElement || this._getElementName(target)) @@ -3177,14 +3167,14 @@ Node.prototype.onKeyDown = function (event) { } else if (keynum === 39) { // Arrow Right if (altKey && !shiftKey) { // Alt + Arrow Right // move to right element - var nextElement = this._nextElement(target) + const nextElement = this._nextElement(target) if (nextElement) { this.focus(this._getElementName(nextElement)) } handled = true } else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow Right dom = firstNode.getDom() - var prevDom = dom.previousSibling + const prevDom = dom.previousSibling if (prevDom) { prevNode = Node.getNodeFromTarget(prevDom) if (prevNode && prevNode.parent && !prevNode.isVisible()) { @@ -3196,7 +3186,7 @@ Node.prototype.onKeyDown = function (event) { oldParentPathRedo = oldParent.getInternalPath() newParentPathRedo = prevNode.parent.getInternalPath() - selectedNodes.forEach(function (node) { + selectedNodes.forEach(node => { prevNode.parent.moveBefore(node, prevNode) }) this.focus(Node.focusElement || this._getElementName(target)) @@ -3270,7 +3260,7 @@ Node.prototype.onKeyDown = function (event) { oldParentPathRedo = oldParent.getInternalPath() newParentPathRedo = nextNode2.parent.getInternalPath() - selectedNodes.forEach(function (node) { + selectedNodes.forEach(node => { nextNode2.parent.moveBefore(node, nextNode2) }) this.focus(Node.focusElement || this._getElementName(target)) @@ -3333,13 +3323,13 @@ Node.prototype._onExpand = function (recurse) { */ Node.prototype._showColorPicker = function () { if (typeof this.editor.options.onColorPicker === 'function' && this.dom.color) { - var node = this + const node = this // force deleting current color picker (if any) node._deleteDomColor() node.updateDom() - var colorAnchor = createAbsoluteAnchor(this.dom.color, this.editor.frame) + const colorAnchor = createAbsoluteAnchor(this.dom.color, this.editor.frame) this.editor.options.onColorPicker(colorAnchor, this.value, function onChange (value) { if (typeof value === 'string' && value !== node.value) { @@ -3362,12 +3352,8 @@ Node.prototype._showColorPicker = function () { Node.prototype.getFieldNames = function (excludeNode) { if (this.type === 'object') { return this.childs - .filter(function (child) { - return child !== excludeNode - }) - .map(function (child) { - return child.field - }) + .filter(child => child !== excludeNode) + .map(child => child.field) } return [] @@ -3377,28 +3363,28 @@ Node.prototype.getFieldNames = function (excludeNode) { * Remove nodes * @param {Node[] | Node} nodes */ -Node.onRemove = function (nodes) { +Node.onRemove = nodes => { if (!Array.isArray(nodes)) { return Node.onRemove([nodes]) } if (nodes && nodes.length > 0) { - var firstNode = nodes[0] - var parent = firstNode.parent - var editor = firstNode.editor - var firstIndex = firstNode.getIndex() + const firstNode = nodes[0] + const parent = firstNode.parent + const editor = firstNode.editor + const firstIndex = firstNode.getIndex() editor.highlighter.unhighlight() // adjust the focus - var oldSelection = editor.getDomSelection() + const oldSelection = editor.getDomSelection() Node.blurNodes(nodes) - var newSelection = editor.getDomSelection() + const newSelection = editor.getDomSelection() // store the paths before removing them (needed for history) - var paths = nodes.map(getInternalPath) + const paths = nodes.map(getInternalPath) // remove the nodes - nodes.forEach(function (node) { + nodes.forEach(node => { node.parent._remove(node) }) @@ -3419,25 +3405,25 @@ Node.onRemove = function (nodes) { * duplicated nodes will be added right after the original nodes * @param {Node[] | Node} nodes */ -Node.onDuplicate = function (nodes) { +Node.onDuplicate = nodes => { if (!Array.isArray(nodes)) { return Node.onDuplicate([nodes]) } if (nodes && nodes.length > 0) { - var lastNode = nodes[nodes.length - 1] - var parent = lastNode.parent - var editor = lastNode.editor + const lastNode = nodes[nodes.length - 1] + const parent = lastNode.parent + const editor = lastNode.editor editor.deselect(editor.multiselection.nodes) // duplicate the nodes - var oldSelection = editor.getDomSelection() - var afterNode = lastNode - var clones = nodes.map(function (node) { - var clone = node.clone() + const oldSelection = editor.getDomSelection() + let afterNode = lastNode + const clones = nodes.map(node => { + const clone = node.clone() if (node.parent.type === 'object') { - var existingFieldNames = node.parent.getFieldNames() + const existingFieldNames = node.parent.getFieldNames() clone.field = util.findUniqueName(node.field, existingFieldNames) } parent.insertAfter(clone, afterNode) @@ -3458,7 +3444,7 @@ Node.onDuplicate = function (nodes) { } else { editor.select(clones) } - var newSelection = editor.getDomSelection() + const newSelection = editor.getDomSelection() editor._onAction('duplicateNodes', { paths: nodes.map(getInternalPath), @@ -3479,21 +3465,21 @@ Node.onDuplicate = function (nodes) { * @private */ Node.prototype._onInsertBefore = function (field, value, type) { - var oldSelection = this.editor.getDomSelection() + const oldSelection = this.editor.getDomSelection() - var newNode = new Node(this.editor, { + const newNode = new Node(this.editor, { field: (field !== undefined) ? field : '', value: (value !== undefined) ? value : '', type: type }) newNode.expand(true) - var beforePath = this.getInternalPath() + const beforePath = this.getInternalPath() this.parent.insertBefore(newNode, this) this.editor.highlighter.unhighlight() newNode.focus('field') - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() this.editor._onAction('insertBeforeNodes', { nodes: [newNode], @@ -3513,9 +3499,9 @@ Node.prototype._onInsertBefore = function (field, value, type) { * @private */ Node.prototype._onInsertAfter = function (field, value, type) { - var oldSelection = this.editor.getDomSelection() + const oldSelection = this.editor.getDomSelection() - var newNode = new Node(this.editor, { + const newNode = new Node(this.editor, { field: (field !== undefined) ? field : '', value: (value !== undefined) ? value : '', type: type @@ -3524,7 +3510,7 @@ Node.prototype._onInsertAfter = function (field, value, type) { this.parent.insertAfter(newNode, this) this.editor.highlighter.unhighlight() newNode.focus('field') - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() this.editor._onAction('insertAfterNodes', { nodes: [newNode], @@ -3544,9 +3530,9 @@ Node.prototype._onInsertAfter = function (field, value, type) { * @private */ Node.prototype._onAppend = function (field, value, type) { - var oldSelection = this.editor.getDomSelection() + const oldSelection = this.editor.getDomSelection() - var newNode = new Node(this.editor, { + const newNode = new Node(this.editor, { field: (field !== undefined) ? field : '', value: (value !== undefined) ? value : '', type: type @@ -3555,7 +3541,7 @@ Node.prototype._onAppend = function (field, value, type) { this.parent.appendChild(newNode) this.editor.highlighter.unhighlight() newNode.focus('field') - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() this.editor._onAction('appendNodes', { nodes: [newNode], @@ -3572,11 +3558,11 @@ Node.prototype._onAppend = function (field, value, type) { * @private */ Node.prototype._onChangeType = function (newType) { - var oldType = this.type + const oldType = this.type if (newType !== oldType) { - var oldSelection = this.editor.getDomSelection() + const oldSelection = this.editor.getDomSelection() this.changeType(newType) - var newSelection = this.editor.getDomSelection() + const newSelection = this.editor.getDomSelection() this.editor._onAction('changeType', { path: this.getInternalPath(), @@ -3607,20 +3593,18 @@ Node.prototype.sort = function (path, direction) { this.hideChilds() // sorting is faster when the childs are not attached to the dom // copy the childs array (the old one will be kept for an undo action - var oldChilds = this.childs + const oldChilds = this.childs this.childs = this.childs.concat() // sort the childs array - var order = (direction === 'desc') ? -1 : 1 + const order = (direction === 'desc') ? -1 : 1 if (this.type === 'object') { - this.childs.sort(function (a, b) { - return order * naturalSort(a.field, b.field) - }) + this.childs.sort((a, b) => order * naturalSort(a.field, b.field)) } else { // this.type === 'array' - this.childs.sort(function (a, b) { - var nodeA = a.getNestedChild(path) - var nodeB = b.getNestedChild(path) + this.childs.sort((a, b) => { + const nodeA = a.getNestedChild(path) + const nodeB = b.getNestedChild(path) if (!nodeA) { return order @@ -3629,8 +3613,8 @@ Node.prototype.sort = function (path, direction) { return -order } - var valueA = nodeA.value - var valueB = nodeB.value + const valueA = nodeA.value + const valueB = nodeB.value if (typeof valueA !== 'string' && typeof valueB !== 'string') { // both values are a number, boolean, or null -> use simple, fast sorting @@ -3658,7 +3642,7 @@ Node.prototype.sort = function (path, direction) { * @param {*} newValue */ Node.prototype.update = function (newValue) { - var oldValue = this.getInternalValue() + const oldValue = this.getInternalValue() this.setValue(newValue) @@ -3677,14 +3661,14 @@ Node.prototype.update = function (newValue) { * @private */ Node.prototype._detachFromDom = function () { - var table = this.dom.tr ? this.dom.tr.parentNode : undefined - var lastTr + const table = this.dom.tr ? this.dom.tr.parentNode : undefined + let lastTr if (this.expanded) { lastTr = this.getAppendDom() } else { lastTr = this.getDom() } - var nextTr = (lastTr && lastTr.parentNode) ? lastTr.nextSibling : undefined + const nextTr = (lastTr && lastTr.parentNode) ? lastTr.nextSibling : undefined this.hide({ resetVisibleChilds: false }) @@ -3727,14 +3711,14 @@ Node.prototype.transform = function (query) { this.hideChilds() // sorting is faster when the childs are not attached to the dom try { - var oldInternalValue = this.getInternalValue() + const oldInternalValue = this.getInternalValue() // apply the JMESPath query - var oldValue = this.getValue() - var newValue = jmespath.search(oldValue, query) + const oldValue = this.getValue() + const newValue = jmespath.search(oldValue, query) this.setValue(newValue) - var newInternalValue = this.getInternalValue() + const newInternalValue = this.getInternalValue() this.editor._onAction('transform', { path: this.getInternalPath(), @@ -3758,9 +3742,9 @@ Node.prototype.extract = function () { this.hideChilds() try { - var oldInternalValue = this.editor.node.getInternalValue() + const oldInternalValue = this.editor.node.getInternalValue() this.editor._setRoot(this) - var newInternalValue = this.editor.node.getInternalValue() + const newInternalValue = this.editor.node.getInternalValue() this.editor._onAction('transform', { path: this.editor.node.getInternalPath(), @@ -3781,8 +3765,8 @@ Node.prototype.extract = function () { * @returns {Node} */ Node.prototype.getNestedChild = function (path) { - var i = 0 - var child = this + let i = 0 + let child = this while (child && i < path.length) { child = child.findChildByProperty(path[i]) @@ -3802,9 +3786,7 @@ Node.prototype.findChildByProperty = function (prop) { return undefined } - return this.childs.find(function (child) { - return child.field === prop - }) + return this.childs.find(child => child.field === prop) } /** @@ -3836,7 +3818,7 @@ Node.prototype.getShowMoreDom = function () { * @return {Node | undefined} node or undefined when not found * @static */ -Node.getNodeFromTarget = function (target) { +Node.getNodeFromTarget = target => { while (target) { if (target.node) { return target.node @@ -3852,11 +3834,11 @@ Node.getNodeFromTarget = function (target) { * @param {HTMLElement} target * @returns {boolean} */ -Node.targetIsColorPicker = function (target) { - var node = Node.getNodeFromTarget(target) +Node.targetIsColorPicker = target => { + const node = Node.getNodeFromTarget(target) if (node) { - var parent = target && target.parentNode + let parent = target && target.parentNode while (parent) { if (parent === node.dom.color) { return true @@ -3873,15 +3855,15 @@ Node.targetIsColorPicker = function (target) { * (b) the node after, or (c) the parent node. * @param {Array. | Node} nodes */ -Node.blurNodes = function (nodes) { +Node.blurNodes = nodes => { if (!Array.isArray(nodes)) { Node.blurNodes([nodes]) return } - var firstNode = nodes[0] - var parent = firstNode.parent - var firstIndex = firstNode.getIndex() + const firstNode = nodes[0] + const parent = firstNode.parent + const firstIndex = firstNode.getIndex() if (parent.childs[firstIndex + nodes.length]) { parent.childs[firstIndex + nodes.length].focus() @@ -3897,7 +3879,7 @@ Node.blurNodes = function (nodes) { * @return {Node} nextSibling */ Node.prototype.nextSibling = function () { - var index = this.parent.childs.indexOf(this) + const index = this.parent.childs.indexOf(this) return this.parent.childs[index + 1] || this.parent.append } @@ -3906,11 +3888,11 @@ Node.prototype.nextSibling = function () { * @return {Node | null} previousNode */ Node.prototype._previousNode = function () { - var prevNode = null - var dom = this.getDom() + let prevNode = null + const dom = this.getDom() if (dom && dom.parentNode) { // find the previous field - var prevDom = dom + let prevDom = dom do { prevDom = prevDom.previousSibling prevNode = Node.getNodeFromTarget(prevDom) @@ -3926,11 +3908,11 @@ Node.prototype._previousNode = function () { * @private */ Node.prototype._nextNode = function () { - var nextNode = null - var dom = this.getDom() + let nextNode = null + const dom = this.getDom() if (dom && dom.parentNode) { // find the previous field - var nextDom = dom + let nextDom = dom do { nextDom = nextDom.nextSibling nextNode = Node.getNodeFromTarget(nextDom) @@ -3947,10 +3929,10 @@ Node.prototype._nextNode = function () { * @private */ Node.prototype._firstNode = function () { - var firstNode = null - var dom = this.getDom() + let firstNode = null + const dom = this.getDom() if (dom && dom.parentNode) { - var firstDom = dom.parentNode.firstChild + const firstDom = dom.parentNode.firstChild firstNode = Node.getNodeFromTarget(firstDom) } @@ -3963,10 +3945,10 @@ Node.prototype._firstNode = function () { * @private */ Node.prototype._lastNode = function () { - var lastNode = null - var dom = this.getDom() + let lastNode = null + const dom = this.getDom() if (dom && dom.parentNode) { - var lastDom = dom.parentNode.lastChild + let lastDom = dom.parentNode.lastChild lastNode = Node.getNodeFromTarget(lastDom) while (lastDom && lastNode && !lastNode.isVisible()) { lastDom = lastDom.previousSibling @@ -3983,7 +3965,7 @@ Node.prototype._lastNode = function () { * @private */ Node.prototype._previousElement = function (elem) { - var dom = this.dom + const dom = this.dom // noinspection FallthroughInSwitchStatementJS switch (elem) { case dom.value: @@ -4015,7 +3997,7 @@ Node.prototype._previousElement = function (elem) { * @private */ Node.prototype._nextElement = function (elem) { - var dom = this.dom + const dom = this.dom // noinspection FallthroughInSwitchStatementJS switch (elem) { case dom.drag: @@ -4072,8 +4054,8 @@ Node.TYPE_TITLES = { } Node.prototype.addTemplates = function (menu, append) { - var node = this - var templates = node.editor.options.templates + const node = this + const templates = node.editor.options.templates if (templates == null) return if (templates.length) { // create a separator @@ -4081,10 +4063,10 @@ Node.prototype.addTemplates = function (menu, append) { type: 'separator' }) } - var appendData = function (name, data) { + const appendData = (name, data) => { node._onAppend(name, data) } - var insertData = function (name, data) { + const insertData = (name, data) => { node._onInsertBefore(name, data) } templates.forEach(function (template) { @@ -4105,9 +4087,9 @@ Node.prototype.addTemplates = function (menu, append) { * is being closed. */ Node.prototype.showContextMenu = function (anchor, onClose) { - var node = this - var titles = Node.TYPE_TITLES - var items = [] + const node = this + const titles = Node.TYPE_TITLES + let items = [] if (this.editable.value) { items.push({ @@ -4199,9 +4181,9 @@ Node.prototype.showContextMenu = function (anchor, onClose) { } // create append button (for last child node only) - var childs = node.parent.childs + const childs = node.parent.childs if (node === childs[childs.length - 1]) { - var appendSubmenu = [ + const appendSubmenu = [ { text: translate('auto'), className: 'jsoneditor-type-auto', @@ -4249,7 +4231,7 @@ Node.prototype.showContextMenu = function (anchor, onClose) { } // create insert button - var insertSubmenu = [ + const insertSubmenu = [ { text: translate('auto'), className: 'jsoneditor-type-auto', @@ -4319,7 +4301,7 @@ Node.prototype.showContextMenu = function (anchor, onClose) { } if (this.editor.options.onCreateMenu) { - var path = node.getPath() + const path = node.getPath() items = this.editor.options.onCreateMenu(items, { type: 'single', @@ -4328,7 +4310,7 @@ Node.prototype.showContextMenu = function (anchor, onClose) { }) } - var menu = new ContextMenu(items, { close: onClose }) + const menu = new ContextMenu(items, { close: onClose }) menu.show(anchor, this.editor.frame) } @@ -4336,13 +4318,13 @@ Node.prototype.showContextMenu = function (anchor, onClose) { * Show sorting modal */ Node.prototype.showSortModal = function () { - var node = this - var container = this.editor.options.modalAnchor || DEFAULT_MODAL_ANCHOR - var json = this.getValue() + const node = this + const container = this.editor.options.modalAnchor || DEFAULT_MODAL_ANCHOR + const json = this.getValue() function onSort (sortedBy) { - var path = sortedBy.path - var pathArray = util.parsePath(path) + const path = sortedBy.path + const pathArray = util.parsePath(path) node.sortedBy = sortedBy node.sort(pathArray, sortedBy.direction) @@ -4355,11 +4337,11 @@ Node.prototype.showSortModal = function () { * Show transform modal */ Node.prototype.showTransformModal = function () { - var node = this + const node = this - var anchor = this.editor.options.modalAnchor || DEFAULT_MODAL_ANCHOR - var json = node.getValue() - showTransformModal(anchor, json, function (query) { + const anchor = this.editor.options.modalAnchor || DEFAULT_MODAL_ANCHOR + const json = node.getValue() + showTransformModal(anchor, json, query => { node.transform(query) }) } @@ -4370,7 +4352,7 @@ Node.prototype.showTransformModal = function () { * @return {String} type Can be 'object', 'array', 'string', 'auto' * @private */ -Node.prototype._getType = function (value) { +Node.prototype._getType = value => { if (value instanceof Array) { return 'array' } @@ -4394,7 +4376,7 @@ Node.prototype._escapeHTML = function (text) { if (typeof text !== 'string') { return String(text) } else { - var htmlEscaped = String(text) + const htmlEscaped = String(text) .replace(/&/g, '&') // must be replaced first! .replace(//g, '>') @@ -4402,8 +4384,8 @@ Node.prototype._escapeHTML = function (text) { .replace(/^ /, ' ') // space at start .replace(/ $/, ' ') // space at end - var json = JSON.stringify(htmlEscaped) - var html = json.substring(1, json.length - 1) + const json = JSON.stringify(htmlEscaped) + let html = json.substring(1, json.length - 1) if (this.editor.options.escapeUnicode === true) { html = util.escapeUnicodeChars(html) } @@ -4418,8 +4400,8 @@ Node.prototype._escapeHTML = function (text) { * @private */ Node.prototype._unescapeHTML = function (escapedText) { - var json = '"' + this._escapeJSON(escapedText) + '"' - var htmlEscaped = util.parse(json) + const json = '"' + this._escapeJSON(escapedText) + '"' + const htmlEscaped = util.parse(json) return htmlEscaped .replace(/</g, '<') @@ -4437,12 +4419,12 @@ Node.prototype._unescapeHTML = function (escapedText) { * @return {String} escapedText * @private */ -Node.prototype._escapeJSON = function (text) { +Node.prototype._escapeJSON = text => { // TODO: replace with some smart regex (only when a new solution is faster!) - var escaped = '' - var i = 0 + let escaped = '' + let i = 0 while (i < text.length) { - var c = text.charAt(i) + let c = text.charAt(i) if (c === '\n') { escaped += '\\n' } else if (c === '\\') { @@ -4470,8 +4452,8 @@ Node.prototype._escapeJSON = function (text) { * @private */ Node.prototype.updateNodeName = function () { - var count = this.childs ? this.childs.length : 0 - var nodeName + const count = this.childs ? this.childs.length : 0 + let nodeName if (this.type === 'object' || this.type === 'array') { if (this.editor.options.onNodeName) { try { @@ -4499,7 +4481,7 @@ Node.prototype.recursivelyUpdateNodeName = function () { if (this.expanded) { this.updateNodeName() if (this.childs !== 'undefined') { - var i + let i for (i in this.childs) { this.childs[i].recursivelyUpdateNodeName() } diff --git a/src/js/NodeHistory.js b/src/js/NodeHistory.js index c6e02fe..711c2ed 100644 --- a/src/js/NodeHistory.js +++ b/src/js/NodeHistory.js @@ -1,6 +1,6 @@ 'use strict' -var util = require('./util') +const util = require('./util') /** * @constructor History @@ -23,13 +23,13 @@ function NodeHistory (editor) { this.actions = { editField: { undo: function (params) { - var parentNode = findNode(params.parentPath) - var node = parentNode.childs[params.index] + const parentNode = findNode(params.parentPath) + const node = parentNode.childs[params.index] node.updateField(params.oldValue) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - var node = parentNode.childs[params.index] + const parentNode = findNode(params.parentPath) + const node = parentNode.childs[params.index] node.updateField(params.newValue) } }, @@ -52,44 +52,44 @@ function NodeHistory (editor) { appendNodes: { undo: function (params) { - var parentNode = findNode(params.parentPath) - params.paths.map(findNode).forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.paths.map(findNode).forEach(node => { parentNode.removeChild(node) }) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - params.nodes.forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.nodes.forEach(node => { parentNode.appendChild(node) }) } }, insertBeforeNodes: { undo: function (params) { - var parentNode = findNode(params.parentPath) - params.paths.map(findNode).forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.paths.map(findNode).forEach(node => { parentNode.removeChild(node) }) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - var beforeNode = findNode(params.beforePath) - params.nodes.forEach(function (node) { + const parentNode = findNode(params.parentPath) + const beforeNode = findNode(params.beforePath) + params.nodes.forEach(node => { parentNode.insertBefore(node, beforeNode) }) } }, insertAfterNodes: { undo: function (params) { - var parentNode = findNode(params.parentPath) - params.paths.map(findNode).forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.paths.map(findNode).forEach(node => { parentNode.removeChild(node) }) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - var afterNode = findNode(params.afterPath) - params.nodes.forEach(function (node) { + const parentNode = findNode(params.parentPath) + let afterNode = findNode(params.afterPath) + params.nodes.forEach(node => { parentNode.insertAfter(node, afterNode) afterNode = node }) @@ -97,34 +97,34 @@ function NodeHistory (editor) { }, removeNodes: { undo: function (params) { - var parentNode = findNode(params.parentPath) - var beforeNode = parentNode.childs[params.index] || parentNode.append - params.nodes.forEach(function (node) { + const parentNode = findNode(params.parentPath) + const beforeNode = parentNode.childs[params.index] || parentNode.append + params.nodes.forEach(node => { parentNode.insertBefore(node, beforeNode) }) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - params.paths.map(findNode).forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.paths.map(findNode).forEach(node => { parentNode.removeChild(node) }) } }, duplicateNodes: { undo: function (params) { - var parentNode = findNode(params.parentPath) - params.clonePaths.map(findNode).forEach(function (node) { + const parentNode = findNode(params.parentPath) + params.clonePaths.map(findNode).forEach(node => { parentNode.removeChild(node) }) }, redo: function (params) { - var parentNode = findNode(params.parentPath) - var afterNode = findNode(params.afterPath) - var nodes = params.paths.map(findNode) - nodes.forEach(function (node) { - var clone = node.clone() + const parentNode = findNode(params.parentPath) + let afterNode = findNode(params.afterPath) + const nodes = params.paths.map(findNode) + nodes.forEach(node => { + const clone = node.clone() if (parentNode.type === 'object') { - var existingFieldNames = parentNode.getFieldNames() + const existingFieldNames = parentNode.getFieldNames() clone.field = util.findUniqueName(node.field, existingFieldNames) } parentNode.insertAfter(clone, afterNode) @@ -134,14 +134,14 @@ function NodeHistory (editor) { }, moveNodes: { undo: function (params) { - var oldParentNode = findNode(params.oldParentPath) - var newParentNode = findNode(params.newParentPath) - var oldBeforeNode = oldParentNode.childs[params.oldIndex] || oldParentNode.append + const oldParentNode = findNode(params.oldParentPath) + const newParentNode = findNode(params.newParentPath) + const oldBeforeNode = oldParentNode.childs[params.oldIndex] || oldParentNode.append // first copy the nodes, then move them - var nodes = newParentNode.childs.slice(params.newIndex, params.newIndex + params.count) + const nodes = newParentNode.childs.slice(params.newIndex, params.newIndex + params.count) - nodes.forEach(function (node, index) { + nodes.forEach((node, index) => { node.field = params.fieldNames[index] oldParentNode.moveBefore(node, oldBeforeNode) }) @@ -153,14 +153,14 @@ function NodeHistory (editor) { } }, redo: function (params) { - var oldParentNode = findNode(params.oldParentPathRedo) - var newParentNode = findNode(params.newParentPathRedo) - var newBeforeNode = newParentNode.childs[params.newIndexRedo] || newParentNode.append + const oldParentNode = findNode(params.oldParentPathRedo) + const newParentNode = findNode(params.newParentPathRedo) + const newBeforeNode = newParentNode.childs[params.newIndexRedo] || newParentNode.append // first copy the nodes, then move them - var nodes = oldParentNode.childs.slice(params.oldIndexRedo, params.oldIndexRedo + params.count) + const nodes = oldParentNode.childs.slice(params.oldIndexRedo, params.oldIndexRedo + params.count) - nodes.forEach(function (node, index) { + nodes.forEach((node, index) => { node.field = params.fieldNames[index] newParentNode.moveBefore(node, newBeforeNode) }) @@ -169,14 +169,14 @@ function NodeHistory (editor) { sort: { undo: function (params) { - var node = findNode(params.path) + const node = findNode(params.path) node.hideChilds() node.childs = params.oldChilds node.updateDom({ updateIndexes: true }) node.showChilds() }, redo: function (params) { - var node = findNode(params.path) + const node = findNode(params.path) node.hideChilds() node.childs = params.newChilds node.updateDom({ updateIndexes: true }) @@ -206,7 +206,7 @@ function NodeHistory (editor) { * The method onChange is executed when the History is changed, and can * be overloaded. */ -NodeHistory.prototype.onChange = function () {} +NodeHistory.prototype.onChange = () => {} /** * Add a new action to the history @@ -268,9 +268,9 @@ NodeHistory.prototype.canRedo = function () { */ NodeHistory.prototype.undo = function () { if (this.canUndo()) { - var obj = this.history[this.index] + const obj = this.history[this.index] if (obj) { - var action = this.actions[obj.action] + const action = this.actions[obj.action] if (action && action.undo) { action.undo(obj.params) if (obj.params.oldSelection) { @@ -298,9 +298,9 @@ NodeHistory.prototype.redo = function () { if (this.canRedo()) { this.index++ - var obj = this.history[this.index] + const obj = this.history[this.index] if (obj) { - var action = this.actions[obj.action] + const action = this.actions[obj.action] if (action && action.redo) { action.redo(obj.params) if (obj.params.newSelection) { diff --git a/src/js/SearchBox.js b/src/js/SearchBox.js index 563b6fe..4a2513f 100644 --- a/src/js/SearchBox.js +++ b/src/js/SearchBox.js @@ -8,7 +8,7 @@ * create the search box */ function SearchBox (editor, container) { - var searchBox = this + const searchBox = this this.editor = editor this.timeout = undefined @@ -18,65 +18,65 @@ function SearchBox (editor, container) { this.dom = {} this.dom.container = container - var wrapper = document.createElement('div') + const wrapper = document.createElement('div') this.dom.wrapper = wrapper wrapper.className = 'jsoneditor-search' container.appendChild(wrapper) - var results = document.createElement('div') + const results = document.createElement('div') this.dom.results = results results.className = 'jsoneditor-results' wrapper.appendChild(results) - var divInput = document.createElement('div') + const divInput = document.createElement('div') this.dom.input = divInput divInput.className = 'jsoneditor-frame' divInput.title = 'Search fields and values' wrapper.appendChild(divInput) - var refreshSearch = document.createElement('button') + const refreshSearch = document.createElement('button') refreshSearch.type = 'button' refreshSearch.className = 'jsoneditor-refresh' divInput.appendChild(refreshSearch) - var search = document.createElement('input') + const search = document.createElement('input') search.type = 'text' this.dom.search = search - search.oninput = function (event) { + search.oninput = event => { searchBox._onDelayedSearch(event) } - search.onchange = function (event) { + search.onchange = event => { // For IE 9 searchBox._onSearch() } - search.onkeydown = function (event) { + search.onkeydown = event => { searchBox._onKeyDown(event) } - search.onkeyup = function (event) { + search.onkeyup = event => { searchBox._onKeyUp(event) } - refreshSearch.onclick = function (event) { + refreshSearch.onclick = event => { search.select() } // TODO: ESC in FF restores the last input, is a FF bug, https://bugzilla.mozilla.org/show_bug.cgi?id=598819 divInput.appendChild(search) - var searchNext = document.createElement('button') + const searchNext = document.createElement('button') searchNext.type = 'button' searchNext.title = 'Next result (Enter)' searchNext.className = 'jsoneditor-next' - searchNext.onclick = function () { + searchNext.onclick = () => { searchBox.next() } divInput.appendChild(searchNext) - var searchPrevious = document.createElement('button') + const searchPrevious = document.createElement('button') searchPrevious.type = 'button' searchPrevious.title = 'Previous result (Shift+Enter)' searchPrevious.className = 'jsoneditor-previous' - searchPrevious.onclick = function () { + searchPrevious.onclick = () => { searchBox.previous() } @@ -90,7 +90,7 @@ function SearchBox (editor, container) { */ SearchBox.prototype.next = function (focus) { if (this.results !== null) { - var index = this.resultIndex !== null ? this.resultIndex + 1 : 0 + let index = this.resultIndex !== null ? this.resultIndex + 1 : 0 if (index > this.results.length - 1) { index = 0 } @@ -105,8 +105,8 @@ SearchBox.prototype.next = function (focus) { */ SearchBox.prototype.previous = function (focus) { if (this.results !== null) { - var max = this.results.length - 1 - var index = this.resultIndex !== null ? this.resultIndex - 1 : max + const max = this.results.length - 1 + let index = this.resultIndex !== null ? this.resultIndex - 1 : max if (index < 0) { index = max } @@ -124,8 +124,8 @@ SearchBox.prototype.previous = function (focus) { SearchBox.prototype._setActiveResult = function (index, focus) { // de-activate current active result if (this.activeResult) { - var prevNode = this.activeResult.node - var prevElem = this.activeResult.elem + const prevNode = this.activeResult.node + const prevElem = this.activeResult.elem if (prevElem === 'field') { delete prevNode.searchFieldActive } else { @@ -144,8 +144,8 @@ SearchBox.prototype._setActiveResult = function (index, focus) { this.resultIndex = index // set new node active - var node = this.results[this.resultIndex].node - var elem = this.results[this.resultIndex].elem + const node = this.results[this.resultIndex].node + const elem = this.results[this.resultIndex].elem if (elem === 'field') { node.searchFieldActive = true } else { @@ -155,7 +155,7 @@ SearchBox.prototype._setActiveResult = function (index, focus) { node.updateDom() // TODO: not so nice that the focus is only set after the animation is finished - node.scrollTo(function () { + node.scrollTo(() => { if (focus) { node.focus(elem) } @@ -183,8 +183,8 @@ SearchBox.prototype._onDelayedSearch = function (event) { // execute the search after a short delay (reduces the number of // search actions while typing in the search text box) this._clearDelay() - var searchBox = this - this.timeout = setTimeout(function (event) { + const searchBox = this + this.timeout = setTimeout(event => { searchBox._onSearch() }, this.delay) } @@ -199,20 +199,20 @@ SearchBox.prototype._onDelayedSearch = function (event) { SearchBox.prototype._onSearch = function (forceSearch) { this._clearDelay() - var value = this.dom.search.value - var text = value.length > 0 ? value : undefined + const value = this.dom.search.value + const text = value.length > 0 ? value : undefined if (text !== this.lastText || forceSearch) { // only search again when changed this.lastText = text this.results = this.editor.search(text) - var MAX_SEARCH_RESULTS = this.results[0] + const MAX_SEARCH_RESULTS = this.results[0] ? this.results[0].node.MAX_SEARCH_RESULTS : Infinity // try to maintain the current active result if this is still part of the new search results - var activeResultIndex = 0 + let activeResultIndex = 0 if (this.activeResult) { - for (var i = 0; i < this.results.length; i++) { + for (let i = 0; i < this.results.length; i++) { if (this.results[i].node === this.activeResult.node) { activeResultIndex = i break @@ -224,7 +224,7 @@ SearchBox.prototype._onSearch = function (forceSearch) { // display search results if (text !== undefined) { - var resultCount = this.results.length + const resultCount = this.results.length if (resultCount === 0) { this.dom.results.innerHTML = 'no results' } else if (resultCount === 1) { @@ -246,7 +246,7 @@ SearchBox.prototype._onSearch = function (forceSearch) { * @private */ SearchBox.prototype._onKeyDown = function (event) { - var keynum = event.which + const keynum = event.which if (keynum === 27) { // ESC this.dom.search.value = '' // clear search @@ -276,7 +276,7 @@ SearchBox.prototype._onKeyDown = function (event) { * @private */ SearchBox.prototype._onKeyUp = function (event) { - var keynum = event.keyCode + const keynum = event.keyCode if (keynum !== 27 && keynum !== 13) { // !show and !Enter this._onDelayedSearch(event) // For IE 9 diff --git a/src/js/TreePath.js b/src/js/TreePath.js index fde1036..6035174 100644 --- a/src/js/TreePath.js +++ b/src/js/TreePath.js @@ -1,8 +1,8 @@ 'use strict' -var ContextMenu = require('./ContextMenu') -var translate = require('./i18n').translate -var util = require('./util') +const ContextMenu = require('./ContextMenu') +const translate = require('./i18n').translate +const util = require('./util') /** * Creates a component that visualize path selection in tree based editors @@ -35,14 +35,14 @@ TreePath.prototype.reset = function () { * */ TreePath.prototype.setPath = function (pathObjs) { - var me = this + const me = this this.path.innerHTML = '' if (pathObjs && pathObjs.length) { - pathObjs.forEach(function (pathObj, idx) { - var pathEl = document.createElement('span') - var sepEl + pathObjs.forEach((pathObj, idx) => { + const pathEl = document.createElement('span') + let sepEl pathEl.className = 'jsoneditor-treepath-element' pathEl.innerText = pathObj.name pathEl.onclick = _onSegmentClick.bind(me, pathObj) @@ -54,17 +54,17 @@ TreePath.prototype.setPath = function (pathObjs) { sepEl.className = 'jsoneditor-treepath-seperator' sepEl.innerHTML = '►' - sepEl.onclick = function () { + sepEl.onclick = () => { me.contentMenuClicked = true - var items = [] - pathObj.children.forEach(function (child) { + const items = [] + pathObj.children.forEach(child => { items.push({ text: child.name, className: 'jsoneditor-type-modes' + (pathObjs[idx + 1] + 1 && pathObjs[idx + 1].name === child.name ? ' jsoneditor-selected' : ''), click: _onContextMenuItemClick.bind(me, pathObj, child.name) }) }) - var menu = new ContextMenu(items) + const menu = new ContextMenu(items) menu.show(sepEl, me.root, true) } @@ -72,13 +72,13 @@ TreePath.prototype.setPath = function (pathObjs) { } if (idx === pathObjs.length - 1) { - var leftRectPos = (sepEl || pathEl).getBoundingClientRect().right + const leftRectPos = (sepEl || pathEl).getBoundingClientRect().right if (me.path.offsetWidth < leftRectPos) { me.path.scrollLeft = leftRectPos } if (me.path.scrollLeft) { - var showAllBtn = document.createElement('span') + const showAllBtn = document.createElement('span') showAllBtn.className = 'jsoneditor-treepath-show-all-btn' showAllBtn.title = 'show all path' showAllBtn.innerHTML = '...' @@ -93,7 +93,7 @@ TreePath.prototype.setPath = function (pathObjs) { me.contentMenuClicked = false util.addClassName(me.path, 'show-all') me.path.style.width = me.path.parentNode.getBoundingClientRect().width - 10 + 'px' - me.path.onblur = function () { + me.path.onblur = () => { if (me.contentMenuClicked) { me.contentMenuClicked = false me.path.focus() diff --git a/src/js/ace/index.js b/src/js/ace/index.js index 2affa72..20efa1b 100644 --- a/src/js/ace/index.js +++ b/src/js/ace/index.js @@ -1,4 +1,4 @@ -var ace +let ace if (window.ace) { // use the already loaded instance of Ace ace = window.ace diff --git a/src/js/ace/theme-jsoneditor.js b/src/js/ace/theme-jsoneditor.js index 086a0c1..db8e662 100644 --- a/src/js/ace/theme-jsoneditor.js +++ b/src/js/ace/theme-jsoneditor.js @@ -28,7 +28,7 @@ * * ***** END LICENSE BLOCK ***** */ -window.ace.define('ace/theme/jsoneditor', ['require', 'exports', 'module', 'ace/lib/dom'], function (acequire, exports, module) { +window.ace.define('ace/theme/jsoneditor', ['require', 'exports', 'module', 'ace/lib/dom'], (acequire, exports, module) => { exports.isDark = false exports.cssClass = 'ace-jsoneditor' exports.cssText = `.ace-jsoneditor .ace_gutter { @@ -139,6 +139,6 @@ text-decoration: underline background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y }` - var dom = acequire('../lib/dom') + const dom = acequire('../lib/dom') dom.importCssString(exports.cssText, exports.cssClass) }) diff --git a/src/js/appendNodeFactory.js b/src/js/appendNodeFactory.js index 5a1b938..65a7f8d 100644 --- a/src/js/appendNodeFactory.js +++ b/src/js/appendNodeFactory.js @@ -1,8 +1,8 @@ 'use strict' -var util = require('./util') -var ContextMenu = require('./ContextMenu') -var translate = require('./i18n').translate +const util = require('./util') +const ContextMenu = require('./ContextMenu') +const translate = require('./i18n').translate /** * A factory function to create an AppendNode, which depends on a Node @@ -30,7 +30,7 @@ function appendNodeFactory (Node) { */ AppendNode.prototype.getDom = function () { // TODO: implement a new solution for the append node - var dom = this.dom + const dom = this.dom if (dom.tr) { return dom.tr @@ -39,7 +39,7 @@ function appendNodeFactory (Node) { this._updateEditability() // a row for the append button - var trAppend = document.createElement('tr') + const trAppend = document.createElement('tr') trAppend.className = 'jsoneditor-append' trAppend.node = this dom.tr = trAppend @@ -51,9 +51,9 @@ function appendNodeFactory (Node) { dom.tdDrag = document.createElement('td') // create context menu - var tdMenu = document.createElement('td') + const tdMenu = document.createElement('td') dom.tdMenu = tdMenu - var menu = document.createElement('button') + const menu = document.createElement('button') menu.type = 'button' menu.className = 'jsoneditor-button jsoneditor-contextmenu' menu.title = 'Click to open the actions menu (Ctrl+M)' @@ -62,8 +62,8 @@ function appendNodeFactory (Node) { } // a cell for the contents (showing text 'empty') - var tdAppend = document.createElement('td') - var domText = document.createElement('div') + const tdAppend = document.createElement('td') + const domText = document.createElement('div') domText.innerHTML = '(' + translate('empty') + ')' domText.className = 'jsoneditor-readonly' tdAppend.appendChild(domText) @@ -79,37 +79,33 @@ function appendNodeFactory (Node) { * Append node doesn't have a path * @returns {null} */ - AppendNode.prototype.getPath = function () { - return null - } + AppendNode.prototype.getPath = () => null /** * Append node doesn't have an index * @returns {null} */ - AppendNode.prototype.getIndex = function () { - return null - } + AppendNode.prototype.getIndex = () => null /** * Update the HTML dom of the Node */ AppendNode.prototype.updateDom = function (options) { - var dom = this.dom - var tdAppend = dom.td + const dom = this.dom + const tdAppend = dom.td if (tdAppend) { tdAppend.style.paddingLeft = (this.getLevel() * 24 + 26) + 'px' // TODO: not so nice hard coded offset } - var domText = dom.text + const domText = dom.text if (domText) { domText.innerHTML = '(' + translate('empty') + ' ' + this.parent.type + ')' } // attach or detach the contents of the append node: // hide when the parent has childs, show when the parent has no childs - var trAppend = dom.tr + const trAppend = dom.tr if (!this.isVisible()) { if (dom.tr.firstChild) { if (dom.tdDrag) { @@ -149,9 +145,9 @@ function appendNodeFactory (Node) { * is being closed. */ AppendNode.prototype.showContextMenu = function (anchor, onClose) { - var node = this - var titles = Node.TYPE_TITLES - var appendSubmenu = [ + const node = this + const titles = Node.TYPE_TITLES + const appendSubmenu = [ { text: translate('auto'), className: 'jsoneditor-type-auto', @@ -186,7 +182,7 @@ function appendNodeFactory (Node) { } ] node.addTemplates(appendSubmenu, true) - var items = [ + let items = [ // create append button { text: translate('appendText'), @@ -201,7 +197,7 @@ function appendNodeFactory (Node) { ] if (this.editor.options.onCreateMenu) { - var path = node.parent.getPath() + const path = node.parent.getPath() items = this.editor.options.onCreateMenu(items, { type: 'append', @@ -210,7 +206,7 @@ function appendNodeFactory (Node) { }) } - var menu = new ContextMenu(items, { close: onClose }) + const menu = new ContextMenu(items, { close: onClose }) menu.show(anchor, this.editor.frame) } @@ -219,12 +215,12 @@ function appendNodeFactory (Node) { * @param {Event} event */ AppendNode.prototype.onEvent = function (event) { - var type = event.type - var target = event.target || event.srcElement - var dom = this.dom + const type = event.type + const target = event.target || event.srcElement + const dom = this.dom // highlight the append nodes parent - var menu = dom.menu + const menu = dom.menu if (target === menu) { if (type === 'mouseover') { this.editor.highlighter.highlight(this.parent) @@ -235,11 +231,11 @@ function appendNodeFactory (Node) { // context menu events if (type === 'click' && target === dom.menu) { - var highlighter = this.editor.highlighter + const highlighter = this.editor.highlighter highlighter.highlight(this.parent) highlighter.lock() util.addClassName(dom.menu, 'jsoneditor-selected') - this.showContextMenu(dom.menu, function () { + this.showContextMenu(dom.menu, () => { util.removeClassName(dom.menu, 'jsoneditor-selected') highlighter.unlock() highlighter.unhighlight() diff --git a/src/js/autocomplete.js b/src/js/autocomplete.js index 76b28cb..8d07e42 100644 --- a/src/js/autocomplete.js +++ b/src/js/autocomplete.js @@ -1,6 +1,6 @@ 'use strict' -var defaultFilterFunction = { +const defaultFilterFunction = { start: function (token, match, config) { return match.indexOf(token) === 0 }, @@ -16,31 +16,31 @@ function completely (config) { config.confirmKeys = config.confirmKeys || [39, 35, 9] // right, end, tab config.caseSensitive = config.caseSensitive || false // autocomplete case sensitive - var fontSize = '' - var fontFamily = '' + let fontSize = '' + let fontFamily = '' - var wrapper = document.createElement('div') + const wrapper = document.createElement('div') wrapper.style.position = 'relative' wrapper.style.outline = '0' wrapper.style.border = '0' wrapper.style.margin = '0' wrapper.style.padding = '0' - var dropDown = document.createElement('div') + const dropDown = document.createElement('div') dropDown.className = 'autocomplete dropdown' dropDown.style.position = 'absolute' dropDown.style.visibility = 'hidden' - var spacer - var leftSide // <-- it will contain the leftSide part of the textfield (the bit that was already autocompleted) - var createDropDownController = function (elem, rs) { - var rows = [] - var ix = 0 - var oldIndex = -1 + let spacer + let leftSide // <-- it will contain the leftSide part of the textfield (the bit that was already autocompleted) + const createDropDownController = (elem, rs) => { + let rows = [] + let ix = 0 + let oldIndex = -1 - var onMouseOver = function () { this.style.outline = '1px solid #ddd' } - var onMouseOut = function () { this.style.outline = '0' } - var onMouseDown = function () { p.hide(); p.onmouseselection(this.__hint, p.rs) } + const onMouseOver = function () { this.style.outline = '1px solid #ddd' } + const onMouseOut = function () { this.style.outline = '0' } + const onMouseDown = function () { p.hide(); p.onmouseselection(this.__hint, p.rs) } var p = { rs: rs, @@ -52,20 +52,18 @@ function completely (config) { elem.style.visibility = 'hidden' ix = 0 elem.innerHTML = '' - var vph = (window.innerHeight || document.documentElement.clientHeight) - var rect = elem.parentNode.getBoundingClientRect() - var distanceToTop = rect.top - 6 // heuristic give 6px - var distanceToBottom = vph - rect.bottom - 6 // distance from the browser border. + const vph = (window.innerHeight || document.documentElement.clientHeight) + const rect = elem.parentNode.getBoundingClientRect() + const distanceToTop = rect.top - 6 // heuristic give 6px + const distanceToBottom = vph - rect.bottom - 6 // distance from the browser border. rows = [] - var filterFn = typeof config.filter === 'function' ? config.filter : defaultFilterFunction[config.filter] + const filterFn = typeof config.filter === 'function' ? config.filter : defaultFilterFunction[config.filter] - var filtered = !filterFn ? [] : array.filter(function (match) { - return filterFn(config.caseSensitive ? token : token.toLowerCase(), config.caseSensitive ? match : match.toLowerCase(), config) - }) + const filtered = !filterFn ? [] : array.filter(match => filterFn(config.caseSensitive ? token : token.toLowerCase(), config.caseSensitive ? match : match.toLowerCase(), config)) - rows = filtered.map(function (row) { - var divRow = document.createElement('div') + rows = filtered.map(row => { + const divRow = document.createElement('div') divRow.className = 'item' // divRow.style.color = config.color; divRow.onmouseover = onMouseOver @@ -119,7 +117,7 @@ function completely (config) { } function setEndOfContenteditable (contentEditableElement) { - var range, selection + let range, selection if (document.createRange) { // Firefox, Chrome, Opera, Safari, IE 9+ range = document.createRange()// Create a range (a range is a like the selection but invisible) @@ -164,7 +162,7 @@ function completely (config) { return spacer.getBoundingClientRect().right } - var rs = { + const rs = { onArrowDown: function () { }, // defaults to no action. onArrowUp: function () { }, // defaults to no action. onEnter: function () { }, // defaults to no action. @@ -213,7 +211,7 @@ function completely (config) { this.elementHint.className = 'autocomplete hint' this.elementHint.style.zIndex = 2 this.elementHint.style.position = 'absolute' - this.elementHint.onfocus = function () { this.element.focus() }.bind(this) + this.elementHint.onfocus = () => { this.element.focus() } if (this.element.addEventListener) { this.element.removeEventListener('keydown', keyDownHandler) @@ -247,18 +245,18 @@ function completely (config) { } }, repaint: function (element) { - var text = element.innerText + let text = element.innerText text = text.replace('\n', '') - var optionsLength = this.options.length + const optionsLength = this.options.length // breaking text in leftSide and token. - var token = text.substring(this.startFrom) + const token = text.substring(this.startFrom) leftSide = text.substring(0, this.startFrom) - for (var i = 0; i < optionsLength; i++) { - var opt = this.options[i] + for (let i = 0; i < optionsLength; i++) { + const opt = this.options[i] if ((!config.caseSensitive && opt.toLowerCase().indexOf(token.toLowerCase()) === 0) || (config.caseSensitive && opt.indexOf(token) === 0)) { // <-- how about upperCase vs. lowercase this.elementHint.innerText = leftSide + token + opt.substring(token.length) @@ -270,7 +268,7 @@ function completely (config) { dropDown.style.left = calculateWidthForText(leftSide) + 'px' dropDownController.refresh(token, this.options) this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + 10 + 'px' - var wasDropDownHidden = (dropDown.style.visibility === 'hidden') + const wasDropDownHidden = (dropDown.style.visibility === 'hidden') if (!wasDropDownHidden) { this.elementHint.style.width = calculateWidthForText(this.elementHint.innerText) + dropDown.clientWidth + 'px' } } } @@ -280,7 +278,7 @@ function completely (config) { var keyDownHandler = function (e) { // console.log("Keydown:" + e.keyCode); e = e || window.event - var keyCode = e.keyCode + const keyCode = e.keyCode if (this.elementHint == null) return @@ -295,7 +293,7 @@ function completely (config) { return } - var text = this.element.innerText + let text = this.element.innerText text = text.replace('\n', '') if (config.confirmKeys.indexOf(keyCode) >= 0) { // (autocomplete triggered) @@ -323,7 +321,7 @@ function completely (config) { if (this.elementHint.innerText.length === 0) { // if there is a hint rs.onEnter() } else { - var wasDropDownHidden = (dropDown.style.visibility === 'hidden') + const wasDropDownHidden = (dropDown.style.visibility === 'hidden') dropDownController.hide() if (wasDropDownHidden) { @@ -364,15 +362,15 @@ function completely (config) { } }.bind(rs) - var onBlurHandler = function (e) { + var onBlurHandler = e => { rs.hideDropDown() // console.log("Lost focus."); } - dropDownController.onmouseselection = function (text, rs) { + dropDownController.onmouseselection = (text, rs) => { rs.element.innerText = rs.elementHint.innerText = leftSide + text rs.hideDropDown() - window.setTimeout(function () { + window.setTimeout(() => { rs.element.focus() setEndOfContenteditable(rs.element) }, 1) diff --git a/src/js/createAbsoluteAnchor.js b/src/js/createAbsoluteAnchor.js index 6445b42..614caae 100644 --- a/src/js/createAbsoluteAnchor.js +++ b/src/js/createAbsoluteAnchor.js @@ -1,4 +1,4 @@ -var util = require('./util') +const util = require('./util') /** * Create an anchor element absolutely positioned in the `parent` @@ -8,14 +8,14 @@ var util = require('./util') * @param [onDestroy(function(anchor)] Callback when the anchor is destroyed * @returns {HTMLElement} */ -exports.createAbsoluteAnchor = function (anchor, parent, onDestroy) { - var root = getRootNode(anchor) - var eventListeners = {} +exports.createAbsoluteAnchor = (anchor, parent, onDestroy) => { + const root = getRootNode(anchor) + const eventListeners = {} - var anchorRect = anchor.getBoundingClientRect() - var frameRect = parent.getBoundingClientRect() + const anchorRect = anchor.getBoundingClientRect() + const frameRect = parent.getBoundingClientRect() - var absoluteAnchor = document.createElement('div') + const absoluteAnchor = document.createElement('div') absoluteAnchor.className = 'jsoneditor-anchor' absoluteAnchor.style.position = 'absolute' absoluteAnchor.style.left = (anchorRect.left - frameRect.left) + 'px' @@ -32,9 +32,9 @@ exports.createAbsoluteAnchor = function (anchor, parent, onDestroy) { // remove all event listeners // all event listeners are supposed to be attached to document. - for (var name in eventListeners) { + for (const name in eventListeners) { if (hasOwnProperty(eventListeners, name)) { - var fn = eventListeners[name] + const fn = eventListeners[name] if (fn) { util.removeEventListener(root, name, fn) } @@ -49,8 +49,8 @@ exports.createAbsoluteAnchor = function (anchor, parent, onDestroy) { } // create and attach event listeners - var destroyIfOutside = function (event) { - var target = event.target + const destroyIfOutside = event => { + const target = event.target if ((target !== absoluteAnchor) && !util.isChildOf(target, absoluteAnchor)) { destroy() } diff --git a/src/js/i18n.js b/src/js/i18n.js index b255ecd..0fdf20e 100644 --- a/src/js/i18n.js +++ b/src/js/i18n.js @@ -4,8 +4,8 @@ require('./polyfills') -var _locales = ['en', 'pt-BR', 'zh-CN', 'tr'] -var _defs = { +const _locales = ['en', 'pt-BR', 'zh-CN', 'tr'] +const _defs = { en: { array: 'Array', auto: 'Auto', @@ -376,14 +376,12 @@ var _defs = { } } -var _defaultLang = 'en' -var _lang -var userLang = typeof navigator !== 'undefined' +const _defaultLang = 'en' +let _lang +const userLang = typeof navigator !== 'undefined' ? navigator.language || navigator.userLanguage : undefined -_lang = _locales.find(function (l) { - return l === userLang -}) +_lang = _locales.find(l => l === userLang) if (!_lang) { _lang = _defaultLang } @@ -397,9 +395,7 @@ module.exports = { if (!lang) { return } - var langFound = _locales.find(function (l) { - return l === lang - }) + const langFound = _locales.find(l => l === lang) if (langFound) { _lang = langFound } else { @@ -410,10 +406,8 @@ module.exports = { if (!languages) { return } - for (var key in languages) { - var langFound = _locales.find(function (l) { - return l === key - }) + for (const key in languages) { + const langFound = _locales.find(l => l === key) if (!langFound) { _locales.push(key) } @@ -424,7 +418,7 @@ module.exports = { if (!lang) { lang = _lang } - var text = _defs[lang][key] + let text = _defs[lang][key] if (data) { for (key in data) { text = text.replace('${' + key + '}', data[key]) diff --git a/src/js/jsonUtils.js b/src/js/jsonUtils.js index e3d98dd..ebb6281 100644 --- a/src/js/jsonUtils.js +++ b/src/js/jsonUtils.js @@ -22,7 +22,7 @@ * @returns {string | undefined} Returns the string representation of the JSON object. */ function stringifyPartial (value, space, limit) { - var _space // undefined by default + let _space // undefined by default if (typeof space === 'number') { if (space > 10) { _space = repeat(' ', 10) @@ -34,7 +34,7 @@ function stringifyPartial (value, space, limit) { _space = space } - var output = stringifyValue(value, _space, '', limit) + const output = stringifyValue(value, _space, '', limit) return output.length > limit ? (slice(output, limit) + '...') @@ -81,11 +81,11 @@ function stringifyValue (value, space, indent, limit) { * @return {string} */ function stringifyArray (array, space, indent, limit) { - var childIndent = space ? (indent + space) : undefined - var str = space ? '[\n' : '[' + const childIndent = space ? (indent + space) : undefined + let str = space ? '[\n' : '[' - for (var i = 0; i < array.length; i++) { - var item = array[i] + for (let i = 0; i < array.length; i++) { + const item = array[i] if (space) { str += childIndent @@ -120,17 +120,17 @@ function stringifyArray (array, space, indent, limit) { * @return {string} */ function stringifyObject (object, space, indent, limit) { - var childIndent = space ? (indent + space) : undefined - var first = true - var str = space ? '{\n' : '{' + const childIndent = space ? (indent + space) : undefined + let first = true + let str = space ? '{\n' : '{' if (typeof object.toJSON === 'function') { return stringifyValue(object.toJSON(), space, indent, limit) } - for (var key in object) { + for (const key in object) { if (hasOwnProperty(object, key)) { - var value = object[key] + const value = object[key] if (first) { first = false @@ -163,7 +163,7 @@ function stringifyObject (object, space, indent, limit) { * @return {string} */ function repeat (text, times) { - var res = '' + let res = '' while (times-- > 0) { res += text } diff --git a/src/js/polyfills.js b/src/js/polyfills.js index ec444ee..3d85a57 100644 --- a/src/js/polyfills.js +++ b/src/js/polyfills.js @@ -1,7 +1,7 @@ if (typeof Element !== 'undefined') { // Polyfill for array remove - (function () { + (() => { function polyfill (item) { if ('remove' in item) { return @@ -26,8 +26,8 @@ if (typeof Element !== 'undefined') { if (!Array.prototype.find) { // eslint-disable-next-line no-extend-native Array.prototype.find = function (callback) { - for (var i = 0; i < this.length; i++) { - var element = this[i] + for (let i = 0; i < this.length; i++) { + const element = this[i] if (callback.call(this, element, i, this)) { return element } diff --git a/src/js/previewmode.js b/src/js/previewmode.js index e7eaac7..9fbb350 100644 --- a/src/js/previewmode.js +++ b/src/js/previewmode.js @@ -1,21 +1,21 @@ 'use strict' -var jmespath = require('jmespath') -var translate = require('./i18n').translate -var ModeSwitcher = require('./ModeSwitcher') -var ErrorTable = require('./ErrorTable') -var textmode = require('./textmode')[0].mixin -var showSortModal = require('./showSortModal') -var showTransformModal = require('./showTransformModal') -var MAX_PREVIEW_CHARACTERS = require('./constants').MAX_PREVIEW_CHARACTERS -var DEFAULT_MODAL_ANCHOR = require('./constants').DEFAULT_MODAL_ANCHOR -var SIZE_LARGE = require('./constants').SIZE_LARGE -var PREVIEW_HISTORY_LIMIT = require('./constants').PREVIEW_HISTORY_LIMIT -var util = require('./util') -var History = require('./History') +const jmespath = require('jmespath') +const translate = require('./i18n').translate +const ModeSwitcher = require('./ModeSwitcher') +const ErrorTable = require('./ErrorTable') +const textmode = require('./textmode')[0].mixin +const showSortModal = require('./showSortModal') +const showTransformModal = require('./showTransformModal') +const MAX_PREVIEW_CHARACTERS = require('./constants').MAX_PREVIEW_CHARACTERS +const DEFAULT_MODAL_ANCHOR = require('./constants').DEFAULT_MODAL_ANCHOR +const SIZE_LARGE = require('./constants').SIZE_LARGE +const PREVIEW_HISTORY_LIMIT = require('./constants').PREVIEW_HISTORY_LIMIT +const util = require('./util') +const History = require('./History') // create a mixin with the functions for text mode -var previewmode = {} +const previewmode = {} /** * Create a JSON document preview, suitable for processing of large documents @@ -48,7 +48,7 @@ previewmode.create = function (container, options) { // determine mode this.mode = 'preview' - var me = this + const me = this this.container = container this.dom = {} @@ -65,7 +65,7 @@ previewmode.create = function (container, options) { this.frame = document.createElement('div') this.frame.className = 'jsoneditor jsoneditor-mode-preview' - this.frame.onclick = function (event) { + this.frame.onclick = event => { // prevent default submit action when the editor is located inside a form event.preventDefault() } @@ -95,13 +95,13 @@ previewmode.create = function (container, options) { this.frame.appendChild(this.menu) // create format button - var buttonFormat = document.createElement('button') + const buttonFormat = document.createElement('button') buttonFormat.type = 'button' buttonFormat.className = 'jsoneditor-format' buttonFormat.title = 'Format JSON data, with proper indentation and line feeds (Ctrl+\\)' this.menu.appendChild(buttonFormat) buttonFormat.onclick = function handleFormat () { - me.executeWithBusyMessage(function () { + me.executeWithBusyMessage(() => { try { me.format() } catch (err) { @@ -111,13 +111,13 @@ previewmode.create = function (container, options) { } // create compact button - var buttonCompact = document.createElement('button') + const buttonCompact = document.createElement('button') buttonCompact.type = 'button' buttonCompact.className = 'jsoneditor-compact' buttonCompact.title = 'Compact JSON data, remove all whitespaces (Ctrl+Shift+\\)' this.menu.appendChild(buttonCompact) buttonCompact.onclick = function handleCompact () { - me.executeWithBusyMessage(function () { + me.executeWithBusyMessage(() => { try { me.compact() } catch (err) { @@ -128,11 +128,11 @@ previewmode.create = function (container, options) { // create sort button if (this.options.enableSort) { - var sort = document.createElement('button') + const sort = document.createElement('button') sort.type = 'button' sort.className = 'jsoneditor-sort' sort.title = translate('sortTitleShort') - sort.onclick = function () { + sort.onclick = () => { me._showSortModal() } this.menu.appendChild(sort) @@ -140,11 +140,11 @@ previewmode.create = function (container, options) { // create transform button if (this.options.enableTransform) { - var transform = document.createElement('button') + const transform = document.createElement('button') transform.type = 'button' transform.title = translate('transformTitleShort') transform.className = 'jsoneditor-transform' - transform.onclick = function () { + transform.onclick = () => { me._showTransformModal() } this.dom.transform = transform @@ -152,14 +152,14 @@ previewmode.create = function (container, options) { } // create repair button - var buttonRepair = document.createElement('button') + const buttonRepair = document.createElement('button') buttonRepair.type = 'button' buttonRepair.className = 'jsoneditor-repair' buttonRepair.title = 'Repair JSON: fix quotes and escape characters, remove comments and JSONP notation, turn JavaScript objects into JSON.' this.menu.appendChild(buttonRepair) - buttonRepair.onclick = function () { + buttonRepair.onclick = () => { if (me.json === undefined) { // only repair if we don't have valid JSON - me.executeWithBusyMessage(function () { + me.executeWithBusyMessage(() => { try { me.repair() } catch (err) { @@ -171,24 +171,23 @@ previewmode.create = function (container, options) { // create history and undo/redo buttons if (this.options.history !== false) { // default option value is true - var onHistoryChange = function () { + const onHistoryChange = () => { me.dom.undo.disabled = !me.history.canUndo() me.dom.redo.disabled = !me.history.canRedo() } - var calculateItemSize = function (item) { - return item.text.length * 2 // times two to account for the json object - } + const calculateItemSize = item => // times two to account for the json object + item.text.length * 2 this.history = new History(onHistoryChange, calculateItemSize, PREVIEW_HISTORY_LIMIT) // create undo button - var undo = document.createElement('button') + const undo = document.createElement('button') undo.type = 'button' undo.className = 'jsoneditor-undo jsoneditor-separator' undo.title = translate('undo') - undo.onclick = function () { - var action = me.history.undo() + undo.onclick = () => { + const action = me.history.undo() if (action) { me._applyHistory(action) } @@ -197,12 +196,12 @@ previewmode.create = function (container, options) { this.dom.undo = undo // create redo button - var redo = document.createElement('button') + const redo = document.createElement('button') redo.type = 'button' redo.className = 'jsoneditor-redo' redo.title = translate('redo') - redo.onclick = function () { - var action = me.history.redo() + redo.onclick = () => { + const action = me.history.redo() if (action) { me._applyHistory(action) } @@ -232,8 +231,8 @@ previewmode.create = function (container, options) { onFocusLine: null, onChangeHeight: function (height) { // TODO: change CSS to using flex box, remove setting height using JavaScript - var statusBarHeight = me.dom.statusBar ? me.dom.statusBar.clientHeight : 0 - var totalHeight = height + statusBarHeight + 1 + const statusBarHeight = me.dom.statusBar ? me.dom.statusBar.clientHeight : 0 + const totalHeight = height + statusBarHeight + 1 me.content.style.marginBottom = (-totalHeight) + 'px' me.content.style.paddingBottom = totalHeight + 'px' } @@ -246,7 +245,7 @@ previewmode.create = function (container, options) { if (options.statusBar) { util.addClassName(this.content, 'has-status-bar') - var statusBar = document.createElement('div') + const statusBar = document.createElement('div') this.dom.statusBar = statusBar statusBar.className = 'jsoneditor-statusbar' this.frame.appendChild(statusBar) @@ -272,7 +271,7 @@ previewmode.create = function (container, options) { } previewmode._renderPreview = function () { - var text = this.getText() + const text = this.getText() this.dom.previewText.nodeValue = util.limitCharacters(text, MAX_PREVIEW_CHARACTERS) @@ -332,31 +331,31 @@ previewmode._onChange = function () { * @private */ previewmode._showSortModal = function () { - var me = this + const me = this function onSort (json, sortedBy) { if (Array.isArray(json)) { - var sortedArray = util.sort(json, sortedBy.path, sortedBy.direction) + const sortedArray = util.sort(json, sortedBy.path, sortedBy.direction) me.sortedBy = sortedBy me._setAndFireOnChange(sortedArray) } if (util.isObject(json)) { - var sortedObject = util.sortObjectKeys(json, sortedBy.direction) + const sortedObject = util.sortObjectKeys(json, sortedBy.direction) me.sortedBy = sortedBy me._setAndFireOnChange(sortedObject) } } - this.executeWithBusyMessage(function () { - var container = me.options.modalAnchor || DEFAULT_MODAL_ANCHOR - var json = me.get() + this.executeWithBusyMessage(() => { + const container = me.options.modalAnchor || DEFAULT_MODAL_ANCHOR + const json = me.get() me._renderPreview() // update array count - showSortModal(container, json, function (sortedBy) { - me.executeWithBusyMessage(function () { + showSortModal(container, json, sortedBy => { + me.executeWithBusyMessage(() => { onSort(json, sortedBy) }, 'sorting...') }, me.sortedBy) @@ -368,16 +367,16 @@ previewmode._showSortModal = function () { * @private */ previewmode._showTransformModal = function () { - var me = this + const me = this - this.executeWithBusyMessage(function () { - var anchor = me.options.modalAnchor || DEFAULT_MODAL_ANCHOR - var json = me.get() + this.executeWithBusyMessage(() => { + const anchor = me.options.modalAnchor || DEFAULT_MODAL_ANCHOR + const json = me.get() me._renderPreview() // update array count - showTransformModal(anchor, json, function (query) { - me.executeWithBusyMessage(function () { - var updatedJson = jmespath.search(json, query) + showTransformModal(anchor, json, query => { + me.executeWithBusyMessage(() => { + const updatedJson = jmespath.search(json, query) me._setAndFireOnChange(updatedJson) }, 'transforming...') }) @@ -407,8 +406,8 @@ previewmode.destroy = function () { * Compact the code in the text editor */ previewmode.compact = function () { - var json = this.get() - var text = JSON.stringify(json) + const json = this.get() + const text = JSON.stringify(json) // we know that in this case the json is still the same, so we pass json too this._setTextAndFireOnChange(text, json) @@ -418,8 +417,8 @@ previewmode.compact = function () { * Format the code in the text editor */ previewmode.format = function () { - var json = this.get() - var text = JSON.stringify(json, null, this.indentation) + const json = this.get() + const text = JSON.stringify(json, null, this.indentation) // we know that in this case the json is still the same, so we pass json too this._setTextAndFireOnChange(text, json) @@ -429,8 +428,8 @@ previewmode.format = function () { * Repair the code in the text editor */ previewmode.repair = function () { - var text = this.getText() - var repairedText = util.repair(text) + const text = this.getText() + const repairedText = util.repair(text) this._setTextAndFireOnChange(repairedText) } @@ -491,7 +490,7 @@ previewmode._setAndFireOnChange = function (json) { */ previewmode.get = function () { if (this.json === undefined) { - var text = this.getText() + const text = this.getText() this.json = util.parse(text) // this can throw an error } @@ -557,8 +556,8 @@ previewmode._setText = function (jsonText, json) { this._renderPreview() if (this.json === undefined) { - var me = this - this.executeWithBusyMessage(function () { + const me = this + this.executeWithBusyMessage(() => { try { // force parsing the json now, else it will be done in validate without feedback me.json = me.get() @@ -609,7 +608,7 @@ previewmode._pushHistory = function () { return } - var action = { + const action = { text: this.text, json: this.json } @@ -624,14 +623,14 @@ previewmode._pushHistory = function () { * @param {string} message */ previewmode.executeWithBusyMessage = function (fn, message) { - var size = this.getText().length + const size = this.getText().length if (size > SIZE_LARGE) { - var me = this + const me = this util.addClassName(me.frame, 'busy') me.dom.busyContent.innerText = message - setTimeout(function () { + setTimeout(() => { fn() util.removeClassName(me.frame, 'busy') me.dom.busyContent.innerText = '' diff --git a/src/js/showMoreNodeFactory.js b/src/js/showMoreNodeFactory.js index 3cf0f5b..33cdd3b 100644 --- a/src/js/showMoreNodeFactory.js +++ b/src/js/showMoreNodeFactory.js @@ -1,6 +1,6 @@ 'use strict' -var translate = require('./i18n').translate +const translate = require('./i18n').translate /** * A factory function to create an ShowMoreNode, which depends on a Node @@ -37,12 +37,12 @@ function showMoreNodeFactory (Node) { // display "show more" if (!this.dom.tr) { - var me = this - var parent = this.parent - var showMoreButton = document.createElement('a') + const me = this + const parent = this.parent + const showMoreButton = document.createElement('a') showMoreButton.appendChild(document.createTextNode(translate('showMore'))) showMoreButton.href = '#' - showMoreButton.onclick = function (event) { + showMoreButton.onclick = event => { // TODO: use callback instead of accessing a method of the parent parent.visibleChilds = Math.floor(parent.visibleChilds / parent.getMaxVisibleChilds() + 1) * parent.getMaxVisibleChilds() @@ -53,10 +53,10 @@ function showMoreNodeFactory (Node) { return false } - var showAllButton = document.createElement('a') + const showAllButton = document.createElement('a') showAllButton.appendChild(document.createTextNode(translate('showAll'))) showAllButton.href = '#' - showAllButton.onclick = function (event) { + showAllButton.onclick = event => { // TODO: use callback instead of accessing a method of the parent parent.visibleChilds = Infinity me.updateDom() @@ -66,8 +66,8 @@ function showMoreNodeFactory (Node) { return false } - var moreContents = document.createElement('div') - var moreText = document.createTextNode(this._getShowMoreText()) + const moreContents = document.createElement('div') + const moreText = document.createTextNode(this._getShowMoreText()) moreContents.className = 'jsoneditor-show-more' moreContents.appendChild(moreText) moreContents.appendChild(showMoreButton) @@ -75,10 +75,10 @@ function showMoreNodeFactory (Node) { moreContents.appendChild(showAllButton) moreContents.appendChild(document.createTextNode('. ')) - var tdContents = document.createElement('td') + const tdContents = document.createElement('td') tdContents.appendChild(moreContents) - var moreTr = document.createElement('tr') + const moreTr = document.createElement('tr') if (this.editor.options.mode === 'tree') { moreTr.appendChild(document.createElement('td')) moreTr.appendChild(document.createElement('td')) @@ -104,7 +104,7 @@ function showMoreNodeFactory (Node) { this.dom.tr.node = this.parent.childs[this.parent.visibleChilds] if (!this.dom.tr.parentNode) { - var nextTr = this.parent._getNextTr() + const nextTr = this.parent._getNextTr() if (nextTr) { nextTr.parentNode.insertBefore(this.dom.tr, nextTr) } @@ -144,7 +144,7 @@ function showMoreNodeFactory (Node) { * @param {Event} event */ ShowMoreNode.prototype.onEvent = function (event) { - var type = event.type + const type = event.type if (type === 'keydown') { this.onKeyDown(event) } diff --git a/src/js/showSortModal.js b/src/js/showSortModal.js index 80a1bdf..3aa2da6 100644 --- a/src/js/showSortModal.js +++ b/src/js/showSortModal.js @@ -1,6 +1,6 @@ -var picoModal = require('picomodal') -var translate = require('./i18n').translate -var util = require('./util') +const picoModal = require('picomodal') +const translate = require('./i18n').translate +const util = require('./util') /** * Show advanced sorting modal @@ -16,15 +16,15 @@ var util = require('./util') * - {'asc' | 'desc'} direction The selected direction */ function showSortModal (container, json, onSort, options) { - var paths = Array.isArray(json) + const paths = Array.isArray(json) ? util.getChildPaths(json) : [''] - var selectedPath = options && options.path && util.contains(paths, options.path) + const selectedPath = options && options.path && util.contains(paths, options.path) ? options.path : paths[0] - var selectedDirection = (options && options.direction) || 'asc' + const selectedDirection = (options && options.direction) || 'asc' - var content = '
' + + const content = '
' + '
' + translate('sort') + '
' + '
' + '' + @@ -75,11 +75,11 @@ function showSortModal (container, json, onSort, options) { }, modalClass: 'jsoneditor-modal jsoneditor-modal-sort' }) - .afterCreate(function (modal) { - var form = modal.modalElem().querySelector('form') - var ok = modal.modalElem().querySelector('#ok') - var field = modal.modalElem().querySelector('#field') - var direction = modal.modalElem().querySelector('#direction') + .afterCreate(modal => { + const form = modal.modalElem().querySelector('form') + const ok = modal.modalElem().querySelector('#ok') + const field = modal.modalElem().querySelector('#field') + const direction = modal.modalElem().querySelector('#direction') function preprocessPath (path) { return (path === '') @@ -89,8 +89,8 @@ function showSortModal (container, json, onSort, options) { : path } - paths.forEach(function (path) { - var option = document.createElement('option') + paths.forEach(path => { + const option = document.createElement('option') option.text = preprocessPath(path) option.value = path field.appendChild(option) @@ -104,11 +104,11 @@ function showSortModal (container, json, onSort, options) { field.value = selectedPath || paths[0] setDirection(selectedDirection || 'asc') - direction.onclick = function (event) { + direction.onclick = event => { setDirection(event.target.getAttribute('data-value')) } - ok.onclick = function (event) { + ok.onclick = event => { event.preventDefault() event.stopPropagation() @@ -124,7 +124,7 @@ function showSortModal (container, json, onSort, options) { form.onsubmit = ok.onclick } }) - .afterClose(function (modal) { + .afterClose(modal => { modal.destroy() }) .show() diff --git a/src/js/showTransformModal.js b/src/js/showTransformModal.js index d2d795d..2db2e59 100644 --- a/src/js/showTransformModal.js +++ b/src/js/showTransformModal.js @@ -1,11 +1,11 @@ -var jmespath = require('jmespath') -var picoModal = require('picomodal') -var Selectr = require('./assets/selectr/selectr') -var translate = require('./i18n').translate -var stringifyPartial = require('./jsonUtils').stringifyPartial -var util = require('./util') -var MAX_PREVIEW_CHARACTERS = require('./constants').MAX_PREVIEW_CHARACTERS -var debounce = util.debounce +const jmespath = require('jmespath') +const picoModal = require('picomodal') +const Selectr = require('./assets/selectr/selectr') +const translate = require('./i18n').translate +const stringifyPartial = require('./jsonUtils').stringifyPartial +const util = require('./util') +const MAX_PREVIEW_CHARACTERS = require('./constants').MAX_PREVIEW_CHARACTERS +const debounce = util.debounce /** * Show advanced filter and transform modal using JMESPath @@ -16,9 +16,9 @@ var debounce = util.debounce * query as callback */ function showTransformModal (container, json, onTransform) { - var value = json + const value = json - var content = '