diff --git a/.eslintrc b/.eslintrc index 76c42539c061c..90770468d6db1 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,6 +2,5 @@ extends: '@elastic/kibana' rules: no-unused-vars: off - prefer-const: off no-extra-semi: off quotes: off diff --git a/src/cli/cluster/worker.js b/src/cli/cluster/worker.js index 4108627edea65..320defcb7e0d5 100644 --- a/src/cli/cluster/worker.js +++ b/src/cli/cluster/worker.js @@ -5,16 +5,16 @@ import { EventEmitter } from 'events'; import { BinderFor, fromRoot } from '../../utils'; -let cliPath = fromRoot('src/cli'); -let baseArgs = _.difference(process.argv.slice(2), ['--no-watch']); -let baseArgv = [process.execPath, cliPath].concat(baseArgs); +const cliPath = fromRoot('src/cli'); +const baseArgs = _.difference(process.argv.slice(2), ['--no-watch']); +const baseArgv = [process.execPath, cliPath].concat(baseArgs); cluster.setupMaster({ exec: cliPath, silent: false }); -let dead = fork => { +const dead = fork => { return fork.isDead() || fork.killed; }; @@ -40,7 +40,7 @@ module.exports = class Worker extends EventEmitter { this.clusterBinder = new BinderFor(cluster); this.processBinder = new BinderFor(process); - let argv = _.union(baseArgv, opts.argv || []); + const argv = _.union(baseArgv, opts.argv || []); this.env = { kbnWorkerType: this.type, kbnWorkerArgv: JSON.stringify(argv) @@ -124,8 +124,8 @@ module.exports = class Worker extends EventEmitter { } flushChangeBuffer() { - let files = _.unique(this.changes.splice(0)); - let prefix = files.length > 1 ? '\n - ' : ''; + const files = _.unique(this.changes.splice(0)); + const prefix = files.length > 1 ? '\n - ' : ''; return files.reduce(function (list, file) { return `${list || ''}${prefix}"${file}"`; }, ''); diff --git a/src/cli/command.js b/src/cli/command.js index 135d03e32b6c1..98997f4bc1100 100644 --- a/src/cli/command.js +++ b/src/cli/command.js @@ -40,15 +40,15 @@ Command.prototype.unknownArgv = function (argv) { * @return {[type]} [description] */ Command.prototype.collectUnknownOptions = function () { - let title = `Extra ${this._name} options`; + const title = `Extra ${this._name} options`; this.allowUnknownOption(); this.getUnknownOptions = function () { - let opts = {}; - let unknowns = this.unknownArgv(); + const opts = {}; + const unknowns = this.unknownArgv(); while (unknowns.length) { - let opt = unknowns.shift().split('='); + const opt = unknowns.shift().split('='); if (opt[0].slice(0, 2) !== '--') { this.error(`${title} "${opt[0]}" must start with "--"`); } @@ -75,14 +75,14 @@ Command.prototype.collectUnknownOptions = function () { }; Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function (parse, argv) { - let opts = parse.call(this, argv); + const opts = parse.call(this, argv); this.unknownArgv(opts.unknown); return opts; }); Command.prototype.action = _.wrap(Command.prototype.action, function (action, fn) { return action.call(this, function (...args) { - let ret = fn.apply(this, args); + const ret = fn.apply(this, args); if (ret && typeof ret.then === 'function') { ret.then(null, function (e) { console.log('FATAL CLI ERROR', e.stack); diff --git a/src/cli/help.js b/src/cli/help.js index 89bc90a24cbd6..b5078aad458fe 100644 --- a/src/cli/help.js +++ b/src/cli/help.js @@ -5,12 +5,12 @@ module.exports = function (command, spaces) { return command.outputHelp(); } - let defCmd = _.find(command.commands, function (cmd) { + const defCmd = _.find(command.commands, function (cmd) { return cmd._name === 'serve'; }); - let desc = !command.description() ? '' : command.description(); - let cmdDef = !defCmd ? '' : `=${defCmd._name}`; + const desc = !command.description() ? '' : command.description(); + const cmdDef = !defCmd ? '' : `=${defCmd._name}`; return ( ` @@ -31,11 +31,11 @@ function indent(str, n) { } function commandsSummary(program) { - let cmds = _.compact(program.commands.map(function (cmd) { - let name = cmd._name; + const cmds = _.compact(program.commands.map(function (cmd) { + const name = cmd._name; if (name === '*') return; - let opts = cmd.options.length ? ' [options]' : ''; - let args = cmd._args.map(function (arg) { + const opts = cmd.options.length ? ' [options]' : ''; + const args = cmd._args.map(function (arg) { return humanReadableArgName(arg); }).join(' '); @@ -45,7 +45,7 @@ function commandsSummary(program) { ]; })); - let cmdLColWidth = cmds.reduce(function (width, cmd) { + const cmdLColWidth = cmds.reduce(function (width, cmd) { return Math.max(width, cmd[0].length); }, 0); @@ -69,6 +69,6 @@ ${indent(cmd.optionHelp(), 2)} } function humanReadableArgName(arg) { - let nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; } diff --git a/src/cli/log.js b/src/cli/log.js index bbbe3f2f21e89..50657ca533028 100644 --- a/src/cli/log.js +++ b/src/cli/log.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import ansicolors from 'ansicolors'; -let log = _.restParam(function (color, label, rest1) { +const log = _.restParam(function (color, label, rest1) { console.log.apply(console, [color(` ${_.trim(label)} `)].concat(rest1)); }); diff --git a/src/cli_plugin/cli.js b/src/cli_plugin/cli.js index 5a09416a9cb1a..3ff2ba328830f 100644 --- a/src/cli_plugin/cli.js +++ b/src/cli_plugin/cli.js @@ -5,8 +5,8 @@ import listCommand from './list'; import installCommand from './install'; import removeCommand from './remove'; -let argv = process.env.kbnWorkerArgv ? JSON.parse(process.env.kbnWorkerArgv) : process.argv.slice(); -let program = new Command('bin/kibana-plugin'); +const argv = process.env.kbnWorkerArgv ? JSON.parse(process.env.kbnWorkerArgv) : process.argv.slice(); +const program = new Command('bin/kibana-plugin'); program .version(pkg.version) @@ -23,7 +23,7 @@ program .command('help ') .description('get the help for a specific command') .action(function (cmdName) { - let cmd = _.find(program.commands, { _name: cmdName }); + const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); @@ -35,7 +35,7 @@ program }); // check for no command name -let subCommand = argv[2] && !String(argv[2][0]).match(/^-|^\.|\//); +const subCommand = argv[2] && !String(argv[2][0]).match(/^-|^\.|\//); if (!subCommand) { program.defaultHelp(); } diff --git a/src/cli_plugin/install/__tests__/index.js b/src/cli_plugin/install/__tests__/index.js index 470d9452a1c12..701247a49492e 100644 --- a/src/cli_plugin/install/__tests__/index.js +++ b/src/cli_plugin/install/__tests__/index.js @@ -8,7 +8,7 @@ describe('kibana cli', function () { describe('commander options', function () { - let program = { + const program = { command: function () { return program; }, description: function () { return program; }, option: function () { return program; }, diff --git a/src/cli_plugin/install/downloaders/file.js b/src/cli_plugin/install/downloaders/file.js index 505a103755e66..bd8233c009614 100644 --- a/src/cli_plugin/install/downloaders/file.js +++ b/src/cli_plugin/install/downloaders/file.js @@ -3,7 +3,7 @@ import { createWriteStream, createReadStream, unlinkSync, statSync } from 'fs'; function openSourceFile({ sourcePath }) { try { - let fileInfo = statSync(sourcePath); + const fileInfo = statSync(sourcePath); const readStream = createReadStream(sourcePath); diff --git a/src/cli_plugin/install/downloaders/http.js b/src/cli_plugin/install/downloaders/http.js index 40069c4cd063e..0b9844a6d9c14 100644 --- a/src/cli_plugin/install/downloaders/http.js +++ b/src/cli_plugin/install/downloaders/http.js @@ -53,7 +53,7 @@ export default async function downloadUrl(logger, sourceUrl, targetPath, timeout const { req, resp } = await sendRequest({ sourceUrl, timeout }); try { - let totalSize = parseFloat(resp.headers['content-length']) || 0; + const totalSize = parseFloat(resp.headers['content-length']) || 0; const progress = new Progress(logger); progress.init(totalSize); diff --git a/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js b/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js index 0e9b064393d15..7ab961a81a0ab 100644 --- a/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js +++ b/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js @@ -8,7 +8,7 @@ let version = pkg.version; describe('plugins/elasticsearch', function () { describe('lib/is_upgradeable', function () { - let server = { + const server = { config: _.constant({ get: function (key) { switch (key) { @@ -44,7 +44,7 @@ describe('plugins/elasticsearch', function () { upgradeDoc('5.0.0-alpha1', '5.0.0', false); it('should handle missing _id field', function () { - let doc = { + const doc = { '_index': '.kibana', '_type': 'config', '_score': 1, @@ -58,7 +58,7 @@ describe('plugins/elasticsearch', function () { }); it('should handle _id of @@version', function () { - let doc = { + const doc = { '_index': '.kibana', '_type': 'config', '_id': '@@version', diff --git a/src/core_plugins/kbn_doc_views/public/views/table.js b/src/core_plugins/kbn_doc_views/public/views/table.js index af201f39c3539..fef633e5827ec 100644 --- a/src/core_plugins/kbn_doc_views/public/views/table.js +++ b/src/core_plugins/kbn_doc_views/public/views/table.js @@ -26,7 +26,7 @@ docViewsRegistry.register(function () { }; $scope.showArrayInObjectsWarning = function (row, field) { - let value = $scope.flattened[field]; + const value = $scope.flattened[field]; return _.isArray(value) && typeof value[0] === 'object'; }; } diff --git a/src/core_plugins/kibana/index.js b/src/core_plugins/kibana/index.js index 6b22f5271fb0a..b31e32d3dd7fd 100644 --- a/src/core_plugins/kibana/index.js +++ b/src/core_plugins/kibana/index.js @@ -30,7 +30,7 @@ module.exports = function (kibana) { ], injectVars: function (server, options) { - let config = server.config(); + const config = server.config(); return { kbnDefaultAppId: config.get('kibana.defaultAppId'), tilemap: config.get('tilemap') diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js index 8135fca9e1b4a..be9ecea4d89b3 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js @@ -28,8 +28,8 @@ app.directive('outputPreview', function () { }); $scope.updateUi = function () { - let left = $scope.oldObject; - let right = $scope.newObject; + const left = $scope.oldObject; + const right = $scope.newObject; let delta = $scope.diffpatch.diff(left, right); if (!delta || $scope.error) delta = {}; diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js index 05f06927a4351..8995042138230 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js @@ -5,11 +5,11 @@ import keysDeep from '../keys_deep'; describe('keys deep', function () { it('should list first level properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2' }; - let expected = [ + const expected = [ 'property1', 'property2' ]; @@ -20,14 +20,14 @@ describe('keys deep', function () { }); it('should list nested properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2', property3: { subProperty1: 'value1.1' } }; - let expected = [ + const expected = [ 'property1', 'property2', 'property3.subProperty1', @@ -40,7 +40,7 @@ describe('keys deep', function () { }); it('should recursivly list nested properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2', property3: { @@ -52,7 +52,7 @@ describe('keys deep', function () { subProperty3: 'value1.3' } }; - let expected = [ + const expected = [ 'property1', 'property2', 'property3.subProperty1', @@ -69,11 +69,11 @@ describe('keys deep', function () { }); it('should list array properties, but not contents', function () { - let object = { + const object = { property1: 'value1', property2: [ 'item1', 'item2' ] }; - let expected = [ + const expected = [ 'property1', 'property2' ]; diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js index 5b5976583f132..a1f26d224dbc8 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js @@ -2,10 +2,10 @@ import _ from 'lodash'; export default function keysDeep(object, base) { let result = []; - let delimitedBase = base ? base + '.' : ''; + const delimitedBase = base ? base + '.' : ''; _.forEach(object, (value, key) => { - let fullKey = delimitedBase + key; + const fullKey = delimitedBase + key; if (_.isPlainObject(value)) { result = result.concat(keysDeep(value, fullKey)); } else { diff --git a/src/core_plugins/kibana/public/management/sections/indices/filebeat/directives/filebeat_wizard.js b/src/core_plugins/kibana/public/management/sections/indices/filebeat/directives/filebeat_wizard.js index fa2967f8cebc3..677de52e740d9 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/filebeat/directives/filebeat_wizard.js +++ b/src/core_plugins/kibana/public/management/sections/indices/filebeat/directives/filebeat_wizard.js @@ -20,11 +20,11 @@ modules.get('apps/management') const ingest = Private(IngestProvider); const $state = this.state = new AppState(); - let notify = new Notifier({ + const notify = new Notifier({ location: 'Add Data' }); - let totalSteps = 4; + const totalSteps = 4; this.stepResults = {}; this.setCurrentStep = (step) => { diff --git a/src/core_plugins/kibana/public/management/sections/indices/upload/directives/upload_wizard.js b/src/core_plugins/kibana/public/management/sections/indices/upload/directives/upload_wizard.js index 92c79fe01d152..31f0888cb5aba 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/upload/directives/upload_wizard.js +++ b/src/core_plugins/kibana/public/management/sections/indices/upload/directives/upload_wizard.js @@ -19,11 +19,11 @@ modules.get('apps/management') const ingest = Private(IngestProvider); const $state = this.state = new AppState(); - let notify = new Notifier({ + const notify = new Notifier({ location: 'Add Data' }); - let totalSteps = 3; + const totalSteps = 3; this.stepResults = {}; this.setCurrentStep = (step) => { diff --git a/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js b/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js index 7444d38384638..6d83ee73f7645 100644 --- a/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js +++ b/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js @@ -36,7 +36,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should set the same default mapping for all non-strings', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); _.forEach(mappings, function (mapping) { if (mapping.type !== 'text') { @@ -50,7 +50,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should give strings a multi-field mapping with a "text" base type', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); _.forEach(mappings, function (mapping) { if (mapping.type === 'text') { @@ -61,7 +61,7 @@ describe('createMappingsFromPatternFields', function () { it('should handle nested fields', function () { testFields.push({name: 'geo.coordinates', type: 'geo_point'}); - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); expect(mappings).to.have.property('geo'); expect(mappings.geo).to.have.property('properties'); @@ -74,7 +74,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should map all number fields as an ES double', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); expect(mappings).to.have.property('bytes'); expect(mappings.bytes).to.have.property('type', 'double'); diff --git a/src/core_plugins/table_vis/public/table_vis_controller.js b/src/core_plugins/table_vis/public/table_vis_controller.js index 15e1cc40ed0b1..55ffd881f75e1 100644 --- a/src/core_plugins/table_vis/public/table_vis_controller.js +++ b/src/core_plugins/table_vis/public/table_vis_controller.js @@ -11,7 +11,7 @@ const module = uiModules.get('kibana/table_vis', ['kibana']); module.controller('KbnTableVisController', function ($scope, Private) { const tabifyAggResponse = Private(AggResponseTabifyTabifyProvider); - let uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; + const uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; assign($scope.vis.params.sort, uiStateSort); $scope.sort = $scope.vis.params.sort; diff --git a/src/core_plugins/tests_bundle/find_source_files.js b/src/core_plugins/tests_bundle/find_source_files.js index c6b6151166cda..1a2938bbacd5d 100644 --- a/src/core_plugins/tests_bundle/find_source_files.js +++ b/src/core_plugins/tests_bundle/find_source_files.js @@ -5,7 +5,7 @@ import { resolve } from 'path'; import { map, fromNode } from 'bluebird'; import glob from 'glob-all'; -let findSourceFiles = async (patterns, cwd = fromRoot('.')) => { +const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { patterns = [].concat(patterns || []); const matches = await fromNode(cb => { diff --git a/src/core_plugins/tests_bundle/index.js b/src/core_plugins/tests_bundle/index.js index 34fe685e4602b..46f52ca91131b 100644 --- a/src/core_plugins/tests_bundle/index.js +++ b/src/core_plugins/tests_bundle/index.js @@ -16,7 +16,7 @@ export default (kibana) => { uiExports: { bundle: async (UiBundle, env, apps, plugins) => { let modules = []; - let config = kibana.config; + const config = kibana.config; const testGlobs = ['src/ui/public/**/*.js']; const testingPluginIds = config.get('tests_bundle.pluginId'); @@ -28,7 +28,7 @@ export default (kibana) => { if (!plugin) throw new Error('Invalid testingPluginId :: unknown plugin ' + pluginId); // add the modules from all of this plugins apps - for (let app of plugin.apps) { + for (const app of plugin.apps) { modules = union(modules, app.getModules()); } @@ -37,7 +37,7 @@ export default (kibana) => { } else { // add the modules from all of the apps - for (let app of apps) { + for (const app of apps) { modules = union(modules, app.getModules()); } @@ -47,7 +47,7 @@ export default (kibana) => { } const testFiles = await findSourceFiles(testGlobs); - for (let f of testFiles) modules.push(f); + for (const f of testFiles) modules.push(f); if (config.get('tests_bundle.instrument')) { env.addPostLoader({ diff --git a/src/fixtures/agg_resp/geohash_grid.js b/src/fixtures/agg_resp/geohash_grid.js index 33a446ff360b2..b627b180964c1 100644 --- a/src/fixtures/agg_resp/geohash_grid.js +++ b/src/fixtures/agg_resp/geohash_grid.js @@ -17,7 +17,7 @@ export default function GeoHashGridAggResponseFixture() { // }, // }); - let geoHashCharts = _.union( + const geoHashCharts = _.union( _.range(48, 57), // 0-9 _.range(65, 90), // A-Z _.range(97, 122) // a-z @@ -25,15 +25,15 @@ export default function GeoHashGridAggResponseFixture() { let totalDocCount = 0; - let tags = _.times(_.random(4, 20), function (i) { + const tags = _.times(_.random(4, 20), function (i) { // random number of tags let docCount = 0; - let buckets = _.times(_.random(40, 200), function () { + const buckets = _.times(_.random(40, 200), function () { return _.sample(geoHashCharts, 3).join(''); }) .sort() .map(function (geoHash) { - let count = _.random(1, 5000); + const count = _.random(1, 5000); totalDocCount += count; docCount += count; diff --git a/src/fixtures/fake_chart_events.js b/src/fixtures/fake_chart_events.js index 383a61c900815..9e4db976c64e6 100644 --- a/src/fixtures/fake_chart_events.js +++ b/src/fixtures/fake_chart_events.js @@ -1,4 +1,4 @@ -let results = {}; +const results = {}; results.timeSeries = { data: { diff --git a/src/fixtures/fake_hierarchical_data.js b/src/fixtures/fake_hierarchical_data.js index 2b1096cc9c271..d7d734214d4fd 100644 --- a/src/fixtures/fake_hierarchical_data.js +++ b/src/fixtures/fake_hierarchical_data.js @@ -1,4 +1,4 @@ -let data = { }; +const data = { }; data.metricOnly = { hits: { total: 1000, hits: [], max_score: 0 }, diff --git a/src/fixtures/fake_row.js b/src/fixtures/fake_row.js index 032fe0f1a9235..c7acfd4446774 100644 --- a/src/fixtures/fake_row.js +++ b/src/fixtures/fake_row.js @@ -1,5 +1,5 @@ import _ from 'lodash'; -let longString = Array(200).join('_'); +const longString = Array(200).join('_'); export default function (id, mapping) { function fakeVals(type) { diff --git a/src/fixtures/logstash_fields.js b/src/fixtures/logstash_fields.js index e4f993da81470..f8e6288cd9751 100644 --- a/src/fixtures/logstash_fields.js +++ b/src/fixtures/logstash_fields.js @@ -1,5 +1,5 @@ function stubbedLogstashFields() { - let sourceData = [ + const sourceData = [ { name: 'bytes', type: 'number', indexed: true, analyzed: true, sortable: true, filterable: true, count: 10 }, { name: 'ssl', type: 'boolean', indexed: true, analyzed: true, sortable: true, filterable: true, count: 20 }, { name: '@timestamp', type: 'date', indexed: true, analyzed: true, sortable: true, filterable: true, count: 30 }, diff --git a/src/fixtures/mock_courier.js b/src/fixtures/mock_courier.js index ef68696693551..942475fccb4e5 100644 --- a/src/fixtures/mock_courier.js +++ b/src/fixtures/mock_courier.js @@ -3,11 +3,11 @@ import sinon from 'auto-release-sinon'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; export default function (Private, Promise) { - let indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); - let getIndexPatternStub = sinon.stub(); + const indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); + const getIndexPatternStub = sinon.stub(); getIndexPatternStub.returns(Promise.resolve(indexPatterns)); - let courier = { + const courier = { indexPatterns: { get: getIndexPatternStub }, getStub: getIndexPatternStub }; diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 5f5b90e38eb3d..7614896cceb6f 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -1,5 +1,5 @@ import _ from 'lodash'; -let keys = {}; +const keys = {}; export default { get: function (path, def) { return keys[path] == null ? def : keys[path]; diff --git a/src/fixtures/stubbed_doc_source_response.js b/src/fixtures/stubbed_doc_source_response.js index 5bed6d41af348..99055142e5bb1 100644 --- a/src/fixtures/stubbed_doc_source_response.js +++ b/src/fixtures/stubbed_doc_source_response.js @@ -1,7 +1,7 @@ import FixturesLogstashFieldsProvider from 'fixtures/logstash_fields'; function stubbedDocSourceResponse(Private) { - let mockLogstashFields = Private(FixturesLogstashFieldsProvider); + const mockLogstashFields = Private(FixturesLogstashFieldsProvider); return function (id, index) { index = index || '.kibana'; diff --git a/src/fixtures/stubbed_logstash_index_pattern.js b/src/fixtures/stubbed_logstash_index_pattern.js index 8377132b6d8ea..daa6b37dc607d 100644 --- a/src/fixtures/stubbed_logstash_index_pattern.js +++ b/src/fixtures/stubbed_logstash_index_pattern.js @@ -3,21 +3,21 @@ import TestUtilsStubIndexPatternProvider from 'test_utils/stub_index_pattern'; import IndexPatternsFieldTypesProvider from 'ui/index_patterns/_field_types'; import FixturesLogstashFieldsProvider from 'fixtures/logstash_fields'; export default function stubbedLogstashIndexPatternService(Private) { - let StubIndexPattern = Private(TestUtilsStubIndexPatternProvider); - let fieldTypes = Private(IndexPatternsFieldTypesProvider); - let mockLogstashFields = Private(FixturesLogstashFieldsProvider); + const StubIndexPattern = Private(TestUtilsStubIndexPatternProvider); + const fieldTypes = Private(IndexPatternsFieldTypesProvider); + const mockLogstashFields = Private(FixturesLogstashFieldsProvider); - let fields = mockLogstashFields.map(function (field) { + const fields = mockLogstashFields.map(function (field) { field.displayName = field.name; - let type = fieldTypes.byName[field.type]; + const type = fieldTypes.byName[field.type]; if (!type) throw new TypeError('unknown type ' + field.type); if (!_.has(field, 'sortable')) field.sortable = type.sortable; if (!_.has(field, 'filterable')) field.filterable = type.filterable; return field; }); - let indexPattern = new StubIndexPattern('logstash-*', 'time', fields); + const indexPattern = new StubIndexPattern('logstash-*', 'time', fields); indexPattern.id = 'logstash-*'; return indexPattern; diff --git a/src/fixtures/stubbed_search_source.js b/src/fixtures/stubbed_search_source.js index 118aaede15047..284a0bf00bbea 100644 --- a/src/fixtures/stubbed_search_source.js +++ b/src/fixtures/stubbed_search_source.js @@ -4,7 +4,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta export default function stubSearchSource(Private, $q, Promise) { let deferedResult = $q.defer(); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); return { sort: sinon.spy(), diff --git a/src/fixtures/vislib/_vis_fixture.js b/src/fixtures/vislib/_vis_fixture.js index 8f06190120053..8fbc2f0f44ac0 100644 --- a/src/fixtures/vislib/_vis_fixture.js +++ b/src/fixtures/vislib/_vis_fixture.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import $ from 'jquery'; import VislibVisProvider from 'ui/vislib/vis'; -let $visCanvas = $('
') +const $visCanvas = $('
') .attr('id', 'vislib-vis-fixtures') .css({ height: '500px', @@ -16,7 +16,7 @@ let $visCanvas = $('
') .appendTo('body'); let count = 0; -let visHeight = $visCanvas.height(); +const visHeight = $visCanvas.height(); $visCanvas.new = function () { count += 1; @@ -32,7 +32,7 @@ afterEach(function () { module.exports = function VislibFixtures(Private) { return function (visLibParams) { - let Vis = Private(VislibVisProvider); + const Vis = Private(VislibVisProvider); return new Vis($visCanvas.new(), _.defaults({}, visLibParams || {}, { shareYAxis: true, addTooltip: true, diff --git a/src/optimize/babel_options.build.js b/src/optimize/babel_options.build.js index 885a318ab84d1..ec3f11f6f1528 100644 --- a/src/optimize/babel_options.build.js +++ b/src/optimize/babel_options.build.js @@ -1,5 +1,5 @@ import { cloneDeep } from 'lodash'; -let fromRoot = require('path').resolve.bind(null, __dirname, '../../'); +const fromRoot = require('path').resolve.bind(null, __dirname, '../../'); if (!process.env.BABEL_CACHE_PATH) { process.env.BABEL_CACHE_PATH = fromRoot('optimize/.babelcache.json'); diff --git a/src/optimize/babel_options.js b/src/optimize/babel_options.js index e562700da3708..903701133ae59 100644 --- a/src/optimize/babel_options.js +++ b/src/optimize/babel_options.js @@ -1,8 +1,8 @@ // this file is not transpiled 'use strict'; // eslint-disable-line strict -let cloneDeep = require('lodash').cloneDeep; -let fromRoot = require('path').resolve.bind(null, __dirname, '../../'); +const cloneDeep = require('lodash').cloneDeep; +const fromRoot = require('path').resolve.bind(null, __dirname, '../../'); if (!process.env.BABEL_CACHE_PATH) { process.env.BABEL_CACHE_PATH = fromRoot('optimize/.babelcache.json'); diff --git a/src/optimize/base_optimizer.js b/src/optimize/base_optimizer.js index 5e0e79d3d72a2..66f3117934da3 100644 --- a/src/optimize/base_optimizer.js +++ b/src/optimize/base_optimizer.js @@ -12,7 +12,7 @@ import { inherits } from 'util'; import { defaults, transform } from 'lodash'; import { resolve } from 'path'; import { writeFile } from 'fs'; -let babelExclude = [/[\/\\](webpackShims|node_modules|bower_components)[\/\\]/]; +const babelExclude = [/[\/\\](webpackShims|node_modules|bower_components)[\/\\]/]; import pkg from '../../package.json'; class BaseOptimizer { @@ -47,14 +47,14 @@ class BaseOptimizer { async initCompiler() { if (this.compiler) return this.compiler; - let compilerConfig = this.getConfig(); + const compilerConfig = this.getConfig(); this.compiler = webpack(compilerConfig); this.compiler.plugin('done', stats => { if (!this.profile) return; - let path = resolve(this.env.workingDir, 'stats.json'); - let content = JSON.stringify(stats.toJson()); + const path = resolve(this.env.workingDir, 'stats.json'); + const content = JSON.stringify(stats.toJson()); writeFile(path, content, function (err) { if (err) throw err; }); @@ -64,8 +64,8 @@ class BaseOptimizer { } getConfig() { - let mapQ = this.sourceMaps ? '?sourceMap' : ''; - let mapQPre = mapQ ? mapQ + '&' : '?'; + const mapQ = this.sourceMaps ? '?sourceMap' : ''; + const mapQPre = mapQ ? mapQ + '&' : '?'; return { context: fromRoot('.'), @@ -177,7 +177,7 @@ class BaseOptimizer { } failedStatsToError(stats) { - let statFormatOpts = { + const statFormatOpts = { hash: false, // add the hash of the compilation version: false, // add webpack version information timings: false, // add timing information @@ -196,7 +196,7 @@ class BaseOptimizer { children: false, }; - let details = stats.toString(defaults({ colors: true }, statFormatOpts)); + const details = stats.toString(defaults({ colors: true }, statFormatOpts)); return Boom.create( 500, diff --git a/src/optimize/fs_optimizer.js b/src/optimize/fs_optimizer.js index 67e03c66c64a8..3e11b34acaed1 100644 --- a/src/optimize/fs_optimizer.js +++ b/src/optimize/fs_optimizer.js @@ -12,7 +12,7 @@ module.exports = class FsOptimizer extends BaseOptimizer { async run() { if (!this.compiler) await this.init(); - let stats = await fromNode(cb => { + const stats = await fromNode(cb => { this.compiler.run((err, stats) => { if (err || !stats) return cb(err); diff --git a/src/optimize/index.js b/src/optimize/index.js index a753ea40f8381..fa0028ffe4204 100644 --- a/src/optimize/index.js +++ b/src/optimize/index.js @@ -10,17 +10,17 @@ module.exports = async (kbnServer, server, config) => { // on the watch setup managed by the cli. It proxies all bundles/* requests to // the other server. The server on 5602 is long running, in order to prevent // complete rebuilds of the optimize content. - let lazy = config.get('optimize.lazy'); + const lazy = config.get('optimize.lazy'); if (lazy) { return await kbnServer.mixin(require('./lazy/lazy')); } - let bundles = kbnServer.bundles; + const bundles = kbnServer.bundles; server.exposeStaticDir('/bundles/{path*}', bundles.env.workingDir); await bundles.writeEntryFiles(); // in prod, only bundle when someing is missing or invalid - let invalidBundles = config.get('optimize.useBundleCache') ? await bundles.getInvalidBundles() : bundles; + const invalidBundles = config.get('optimize.useBundleCache') ? await bundles.getInvalidBundles() : bundles; // we might not have any work to do if (!invalidBundles.getIds().length) { @@ -32,7 +32,7 @@ module.exports = async (kbnServer, server, config) => { } // only require the FsOptimizer when we need to - let optimizer = new FsOptimizer({ + const optimizer = new FsOptimizer({ env: bundles.env, bundles: bundles, profile: config.get('optimize.profile'), @@ -46,9 +46,9 @@ module.exports = async (kbnServer, server, config) => { `Optimizing and caching ${bundles.desc()}. This may take a few minutes` ); - let start = Date.now(); + const start = Date.now(); await optimizer.run(); - let seconds = ((Date.now() - start) / 1000).toFixed(2); + const seconds = ((Date.now() - start) / 1000).toFixed(2); server.log(['info', 'optimize'], `Optimization of ${bundles.desc()} complete in ${seconds} seconds`); }; diff --git a/src/optimize/lazy/lazy_optimizer.js b/src/optimize/lazy/lazy_optimizer.js index ca7b052e392f6..62c4e2cec0e06 100644 --- a/src/optimize/lazy/lazy_optimizer.js +++ b/src/optimize/lazy/lazy_optimizer.js @@ -41,7 +41,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { return; } - let err = this.failedStatsToError(stats); + const err = this.failedStatsToError(stats); this.logRunFailure(err); this.build.failure(err); this.watching.invalidate(); @@ -54,7 +54,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { } }); - let buildPromise = this.build.get(); + const buildPromise = this.build.get(); if (this.prebuild) await buildPromise; this.initializing = false; @@ -75,7 +75,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { method: 'GET', handler: async (request, reply) => { try { - let path = await this.getPath(request.params.asset); + const path = await this.getPath(request.params.asset); return reply.file(path); } catch (error) { console.log(error.stack); diff --git a/src/optimize/lazy/optmzr_role.js b/src/optimize/lazy/optmzr_role.js index 8c6a653fe0937..30f5f30ac73de 100644 --- a/src/optimize/lazy/optmzr_role.js +++ b/src/optimize/lazy/optmzr_role.js @@ -3,7 +3,7 @@ import LazyOptimizer from './lazy_optimizer'; import { fromRoot } from '../../utils'; export default async (kbnServer, kibanaHapiServer, config) => { - let server = new LazyServer( + const server = new LazyServer( config.get('optimize.lazyHost'), config.get('optimize.lazyPort'), new LazyOptimizer({ @@ -20,7 +20,7 @@ export default async (kbnServer, kibanaHapiServer, config) => { let ready = false; - let sendReady = () => { + const sendReady = () => { if (!process.connected) return; process.send(['WORKER_BROADCAST', { optimizeReady: ready }]); }; diff --git a/src/optimize/lazy/proxy_role.js b/src/optimize/lazy/proxy_role.js index b9b0f26ed6a63..9ea0bceeec7c3 100644 --- a/src/optimize/lazy/proxy_role.js +++ b/src/optimize/lazy/proxy_role.js @@ -18,11 +18,11 @@ module.exports = (kbnServer, server, config) => { }); return fromNode(cb => { - let timeout = setTimeout(() => { + const timeout = setTimeout(() => { cb(new Error('Server timedout waiting for the optimizer to become ready')); }, config.get('optimize.lazyProxyTimeout')); - let waiting = once(() => { + const waiting = once(() => { server.log(['info', 'optimize'], 'Waiting for optimizer completion'); }); diff --git a/src/optimize/lazy/weird_control_flow.js b/src/optimize/lazy/weird_control_flow.js index ae37cce688283..b6ca267cdc720 100644 --- a/src/optimize/lazy/weird_control_flow.js +++ b/src/optimize/lazy/weird_control_flow.js @@ -51,7 +51,7 @@ module.exports = class WeirdControlFlow { } _flush(args) { - for (let fn of this.handlers.splice(0)) { + for (const fn of this.handlers.splice(0)) { fn.apply(null, args); } } diff --git a/src/server/config/__tests__/config.js b/src/server/config/__tests__/config.js index 0dc60f98f6004..ab2cc65bed201 100644 --- a/src/server/config/__tests__/config.js +++ b/src/server/config/__tests__/config.js @@ -14,7 +14,7 @@ import Joi from 'joi'; * */ -let data = { +const data = { test: { hosts: ['host-01', 'host-02'], client: { @@ -25,7 +25,7 @@ let data = { } }; -let schema = Joi.object({ +const schema = Joi.object({ test: Joi.object({ enable: Joi.boolean().default(true), hosts: Joi.array().items(Joi.string()), @@ -44,39 +44,39 @@ describe('lib/config/config', function () { describe('constructor', function () { it('should not allow any config if the schema is not passed', function () { - let config = new Config(); - let run = function () { + const config = new Config(); + const run = function () { config.set('something.enable', true); }; expect(run).to.throwException(); }); it('should allow keys in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('test.client.host', 'http://localhost'); }; expect(run).to.not.throwException(); }); it('should not allow keys not in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('paramNotDefinedInTheSchema', true); }; expect(run).to.throwException(); }); it('should not allow child keys not in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('test.client.paramNotDefinedInTheSchema', true); }; expect(run).to.throwException(); }); it('should set defaults', function () { - let config = new Config(schema); + const config = new Config(schema); expect(config.get('test.enable')).to.be(true); expect(config.get('test.client.type')).to.be('datastore'); }); @@ -92,7 +92,7 @@ describe('lib/config/config', function () { it('should reset the config object with new values', function () { config.set(data); - let newData = config.get(); + const newData = config.get(); newData.test.enable = false; config.resetTo(newData); expect(config.get()).to.eql(newData); @@ -134,21 +134,21 @@ describe('lib/config/config', function () { }); it('should use an object to set config values', function () { - let hosts = ['host-01', 'host-02']; + const hosts = ['host-01', 'host-02']; config.set({ test: { enable: false, hosts: hosts } }); expect(config.get('test.enable')).to.be(false); expect(config.get('test.hosts')).to.eql(hosts); }); it('should use a flatten object to set config values', function () { - let hosts = ['host-01', 'host-02']; + const hosts = ['host-01', 'host-02']; config.set({ 'test.enable': false, 'test.hosts': hosts }); expect(config.get('test.enable')).to.be(false); expect(config.get('test.hosts')).to.eql(hosts); }); it('should override values with just the values present', function () { - let newData = _.cloneDeep(data); + const newData = _.cloneDeep(data); config.set(data); newData.test.enable = false; config.set({ test: { enable: false } }); @@ -156,7 +156,7 @@ describe('lib/config/config', function () { }); it('should thow an exception when setting a value with the wrong type', function (done) { - let run = function () { + const run = function () { config.set('test.enable', 'something'); }; expect(run).to.throwException(function (err) { @@ -179,7 +179,7 @@ describe('lib/config/config', function () { }); it('should return the whole config object when called without a key', function () { - let newData = _.cloneDeep(data); + const newData = _.cloneDeep(data); newData.test.enable = true; expect(config.get()).to.eql(newData); }); @@ -194,14 +194,14 @@ describe('lib/config/config', function () { }); it('should throw exception for unknown config values', function () { - let run = function () { + const run = function () { config.get('test.does.not.exist'); }; expect(run).to.throwException(/Unknown config key: test.does.not.exist/); }); it('should not throw exception for undefined known config values', function () { - let run = function getUndefValue() { + const run = function getUndefValue() { config.get('test.undefValue'); }; expect(run).to.not.throwException(); @@ -216,13 +216,13 @@ describe('lib/config/config', function () { }); it('should allow you to extend the schema at the top level', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema('myTest', newSchema); expect(config.get('myTest.test')).to.be(true); }); it('should allow you to extend the schema with a prefix', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema('prefix.myTest', newSchema); expect(config.get('prefix')).to.eql({ myTest: { test: true }}); expect(config.get('prefix.myTest')).to.eql({ test: true }); @@ -230,8 +230,8 @@ describe('lib/config/config', function () { }); it('should NOT allow you to extend the schema if somethign else is there', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); - let run = function () { + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const run = function () { config.extendSchema('test', newSchema); }; expect(run).to.throwException(); @@ -241,7 +241,7 @@ describe('lib/config/config', function () { describe('#removeSchema(key)', function () { it('should completely remove the key', function () { - let config = new Config(Joi.object().keys({ + const config = new Config(Joi.object().keys({ a: Joi.number().default(1) })); @@ -251,7 +251,7 @@ describe('lib/config/config', function () { }); it('only removes existing keys', function () { - let config = new Config(Joi.object()); + const config = new Config(Joi.object()); expect(() => config.removeSchema('b')).to.throwException('Unknown schema'); }); diff --git a/src/server/config/__tests__/explode_by.js b/src/server/config/__tests__/explode_by.js index 3514413e575b6..52ab03e00d047 100644 --- a/src/server/config/__tests__/explode_by.js +++ b/src/server/config/__tests__/explode_by.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('explode_by(dot, flatObject)', function () { it('should explode a flatten object with dots', function () { - let flatObject = { + const flatObject = { 'test.enable': true, 'test.hosts': ['host-01', 'host-02'] }; @@ -17,7 +17,7 @@ describe('explode_by(dot, flatObject)', function () { }); it('should explode a flatten object with slashes', function () { - let flatObject = { + const flatObject = { 'test/enable': true, 'test/hosts': ['host-01', 'host-02'] }; diff --git a/src/server/config/__tests__/flatten_with.js b/src/server/config/__tests__/flatten_with.js index 9dc40fc08097e..78864e490bc30 100644 --- a/src/server/config/__tests__/flatten_with.js +++ b/src/server/config/__tests__/flatten_with.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('flatten_with(dot, nestedObj)', function () { it('should flatten object with dot', function () { - let nestedObj = { + const nestedObj = { test: { enable: true, hosts: ['host-01', 'host-02'], diff --git a/src/server/config/__tests__/override.js b/src/server/config/__tests__/override.js index 18b3117dcbe56..055e09d2f0f9f 100644 --- a/src/server/config/__tests__/override.js +++ b/src/server/config/__tests__/override.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('override(target, source)', function () { it('should override the values form source to target', function () { - let target = { + const target = { test: { enable: true, host: ['host-01', 'host-02'], @@ -13,7 +13,7 @@ describe('override(target, source)', function () { } } }; - let source = { test: { client: { type: 'nosql' } } }; + const source = { test: { client: { type: 'nosql' } } }; expect(override(target, source)).to.eql({ test: { enable: true, diff --git a/src/server/config/complete.js b/src/server/config/complete.js index be44448733782..aca586e81f9db 100644 --- a/src/server/config/complete.js +++ b/src/server/config/complete.js @@ -4,8 +4,8 @@ export default function (kbnServer, server, config) { return kbnServer.config; }); - let tmpl = 'Settings for "<%= key %>" were not applied, check for spelling errors and ensure the plugin is loaded.'; - for (let [key, val] of config.getPendingSets()) { + const tmpl = 'Settings for "<%= key %>" were not applied, check for spelling errors and ensure the plugin is loaded.'; + for (const [key, val] of config.getPendingSets()) { server.log(['warning', 'config'], { key, val, tmpl }); } }; diff --git a/src/server/config/config.js b/src/server/config/config.js index 28c8ea4158138..db6b3520b776c 100644 --- a/src/server/config/config.js +++ b/src/server/config/config.js @@ -42,7 +42,7 @@ module.exports = class Config { _.set(this[schemaExts], key, extension); this[schema] = null; - let initialVals = _.get(this[pendingSets], key); + const initialVals = _.get(this[pendingSets], key); if (initialVals) { this.set(key, initialVals); unset(this[pendingSets], key); @@ -86,11 +86,11 @@ module.exports = class Config { if (_.isObject(env)) env = env.name; if (!env) env = process.env.NODE_ENV || 'production'; - let dev = env === 'development'; - let prod = env === 'production'; + const dev = env === 'development'; + const prod = env === 'production'; // pass the environment as context so that it can be refed in config - let context = { + const context = { env: env, prod: prod, dev: dev, @@ -107,7 +107,7 @@ module.exports = class Config { ); } - let results = Joi.validate(newVals, this.getSchema(), { context }); + const results = Joi.validate(newVals, this.getSchema(), { context }); if (results.error) { throw results.error; @@ -121,7 +121,7 @@ module.exports = class Config { return clone(this[vals]); } - let value = _.get(this[vals], key); + const value = _.get(this[vals], key); if (value === undefined) { if (!this.has(key)) { throw new Error('Unknown config key: ' + key); @@ -138,7 +138,7 @@ module.exports = class Config { // Only go deep on inner objects with children if (_.size(schema._inner.children)) { for (let i = 0; i < schema._inner.children.length; i++) { - let child = schema._inner.children[i]; + const child = schema._inner.children[i]; // If the child is an object recurse through it's children and return // true if there's a match if (child.schema._type === 'object') { diff --git a/src/server/config/explode_by.js b/src/server/config/explode_by.js index 50e2b2e82615f..a2e632ddf2a68 100644 --- a/src/server/config/explode_by.js +++ b/src/server/config/explode_by.js @@ -1,10 +1,10 @@ import _ from 'lodash'; module.exports = function (dot, flatObject) { - let fullObject = {}; + const fullObject = {}; _.each(flatObject, function (value, key) { - let keys = key.split(dot); + const keys = key.split(dot); (function walk(memo, keys, value) { - let _key = keys.shift(); + const _key = keys.shift(); if (keys.length === 0) { memo[_key] = value; } else { diff --git a/src/server/config/flatten_with.js b/src/server/config/flatten_with.js index 1401e12f0fb85..ede084f56a3fc 100644 --- a/src/server/config/flatten_with.js +++ b/src/server/config/flatten_with.js @@ -1,7 +1,7 @@ import _ from 'lodash'; module.exports = function (dot, nestedObj, flattenArrays) { - let stack = []; // track key stack - let flatObj = {}; + const stack = []; // track key stack + const flatObj = {}; (function flattenObj(obj) { _.keys(obj).forEach(function (key) { stack.push(key); diff --git a/src/server/config/override.js b/src/server/config/override.js index ef850a32754ae..3354fd5956fe7 100644 --- a/src/server/config/override.js +++ b/src/server/config/override.js @@ -3,8 +3,8 @@ import flattenWith from './flatten_with'; import explodeBy from './explode_by'; module.exports = function (target, source) { - let _target = flattenWith('.', target); - let _source = flattenWith('.', source); + const _target = flattenWith('.', target); + const _source = flattenWith('.', source); return explodeBy('.', _.defaults(_source, _target)); }; diff --git a/src/server/http/index.js b/src/server/http/index.js index b6440bec66044..8ddb933f5cd5c 100644 --- a/src/server/http/index.js +++ b/src/server/http/index.js @@ -65,7 +65,7 @@ module.exports = async function (kbnServer, server, config) { // attach the app name to the server, so we can be sure we are actually talking to kibana server.ext('onPreResponse', function (req, reply) { - let response = req.response; + const response = req.response; if (response.isBoom) { response.output.headers['kbn-name'] = kbnServer.name; @@ -93,7 +93,7 @@ module.exports = async function (kbnServer, server, config) { method: 'GET', path: '/{p*}', handler: function (req, reply) { - let path = req.path; + const path = req.path; if (path === '/' || path.charAt(path.length - 1) !== '/') { return reply(Boom.notFound()); } diff --git a/src/server/kbn_server.js b/src/server/kbn_server.js index 8ad9d9c0709d8..3a7af43975953 100644 --- a/src/server/kbn_server.js +++ b/src/server/kbn_server.js @@ -6,7 +6,7 @@ import { fromRoot, pkg } from '../utils'; import Config from './config/config'; import loggingConfiguration from './logging/configuration'; -let rootDir = fromRoot('.'); +const rootDir = fromRoot('.'); module.exports = class KbnServer { constructor(settings) { @@ -66,7 +66,7 @@ module.exports = class KbnServer { * @return {Promise} - promise that is resolved when the final mixin completes. */ async mixin(...fns) { - for (let fn of compact(flatten(fns))) { + for (const fn of compact(flatten(fns))) { await fn.call(this, this, this.server, this.config); } } @@ -78,7 +78,7 @@ module.exports = class KbnServer { * @return undefined */ async listen() { - let { server, config } = this; + const { server, config } = this; await this.ready(); await fromNode(cb => server.start(cb)); diff --git a/src/server/logging/__tests__/apply_filters_to_keys.js b/src/server/logging/__tests__/apply_filters_to_keys.js index 0175b90ff221b..02c3efab19b43 100644 --- a/src/server/logging/__tests__/apply_filters_to_keys.js +++ b/src/server/logging/__tests__/apply_filters_to_keys.js @@ -3,7 +3,7 @@ import expect from 'expect.js'; describe('applyFiltersToKeys(obj, actionsByKey)', function () { it('applies for each key+prop in actionsByKey', function () { - let data = applyFiltersToKeys({ + const data = applyFiltersToKeys({ a: { b: { c: 1 diff --git a/src/server/logging/apply_filters_to_keys.js b/src/server/logging/apply_filters_to_keys.js index bc85f2fd1f555..19dc6e5d154d8 100644 --- a/src/server/logging/apply_filters_to_keys.js +++ b/src/server/logging/apply_filters_to_keys.js @@ -7,7 +7,7 @@ function replacer(match, group) { } function apply(obj, key, action) { - for (let k in obj) { + for (const k in obj) { if (obj.hasOwnProperty(k)) { let val = obj[k]; if (k === key) { @@ -21,9 +21,9 @@ function apply(obj, key, action) { obj[k] = ('' + val).replace(/./g, 'X'); } else if (/\/.+\//.test(action)) { - let matches = action.match(/\/(.+)\//); + const matches = action.match(/\/(.+)\//); if (matches) { - let regex = new RegExp(matches[1]); + const regex = new RegExp(matches[1]); obj[k] = ('' + val).replace(regex, replacer); } } diff --git a/src/server/logging/configuration.js b/src/server/logging/configuration.js index 2a894a0d97e44..be66a2e738c8b 100644 --- a/src/server/logging/configuration.js +++ b/src/server/logging/configuration.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import logReporter from './log_reporter'; export default function loggingConfiguration(config) { - let events = config.get('logging.events'); + const events = config.get('logging.events'); if (config.get('logging.silent')) { _.defaults(events, {}); diff --git a/src/server/logging/log_format.js b/src/server/logging/log_format.js index 7d11c59abd265..7a077ecdd5c27 100644 --- a/src/server/logging/log_format.js +++ b/src/server/logging/log_format.js @@ -18,7 +18,7 @@ function serializeError(err) { }; } -let levelColor = function (code) { +const levelColor = function (code) { if (code < 299) return ansicolors.green(code); if (code < 399) return ansicolors.yellow(code); if (code < 499) return ansicolors.magenta(code); @@ -41,13 +41,13 @@ module.exports = class TransformObjStream extends Stream.Transform { } _transform(event, enc, next) { - let data = this.filter(this.readEvent(event)); + const data = this.filter(this.readEvent(event)); this.push(this.format(data) + '\n'); next(); } readEvent(event) { - let data = { + const data = { type: event.event, '@timestamp': moment.utc(event.timestamp).format(), tags: [].concat(event.tags || []), @@ -82,7 +82,7 @@ module.exports = class TransformObjStream extends Stream.Transform { contentLength: contentLength }; - let query = querystring.stringify(event.query); + const query = querystring.stringify(event.query); if (query) data.req.url += '?' + query; diff --git a/src/server/logging/log_format_json.js b/src/server/logging/log_format_json.js index 7df528ab968bb..440982bbd3ea7 100644 --- a/src/server/logging/log_format_json.js +++ b/src/server/logging/log_format_json.js @@ -1,7 +1,7 @@ import LogFormat from './log_format'; import stringify from 'json-stringify-safe'; -let stripColors = function (string) { +const stripColors = function (string) { return string.replace(/\u001b[^m]+m/g, ''); }; diff --git a/src/server/logging/log_format_string.js b/src/server/logging/log_format_string.js index 189738a1b4c52..b333510f53ace 100644 --- a/src/server/logging/log_format_string.js +++ b/src/server/logging/log_format_string.js @@ -4,7 +4,7 @@ import moment from 'moment'; import LogFormat from './log_format'; -let statuses = [ +const statuses = [ 'err', 'info', 'error', @@ -14,7 +14,7 @@ let statuses = [ 'debug' ]; -let typeColors = { +const typeColors = { log: 'blue', req: 'green', res: 'green', @@ -34,22 +34,22 @@ let typeColors = { listening: 'magenta' }; -let color = _.memoize(function (name) { +const color = _.memoize(function (name) { return ansicolors[typeColors[name]] || _.identity; }); -let type = _.memoize(function (t) { +const type = _.memoize(function (t) { return color(t)(_.pad(t, 7).slice(0, 7)); }); -let workerType = process.env.kbnWorkerType ? `${type(process.env.kbnWorkerType)} ` : ''; +const workerType = process.env.kbnWorkerType ? `${type(process.env.kbnWorkerType)} ` : ''; module.exports = class KbnLoggerJsonFormat extends LogFormat { format(data) { - let time = color('time')(moment(data.timestamp).format('HH:mm:ss.SSS')); - let msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); + const time = color('time')(moment(data.timestamp).format('HH:mm:ss.SSS')); + const msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); - let tags = _(data.tags) + const tags = _(data.tags) .sortBy(function (tag) { if (color(tag) === _.identity) return `2${tag}`; if (_.includes(statuses, tag)) return `0${tag}`; diff --git a/src/server/pid/index.js b/src/server/pid/index.js index 7d7c1dbdea0fb..a2dc452480e09 100644 --- a/src/server/pid/index.js +++ b/src/server/pid/index.js @@ -2,19 +2,19 @@ import _ from 'lodash'; import Boom from 'boom'; import Promise from 'bluebird'; import { unlinkSync as unlink } from 'fs'; -let writeFile = Promise.promisify(require('fs').writeFile); +const writeFile = Promise.promisify(require('fs').writeFile); module.exports = Promise.method(function (kbnServer, server, config) { - let path = config.get('pid.file'); + const path = config.get('pid.file'); if (!path) return; - let pid = String(process.pid); + const pid = String(process.pid); return writeFile(path, pid, { flag: 'wx' }) .catch(function (err) { if (err.code !== 'EEXIST') throw err; - let log = { + const log = { tmpl: 'pid file already exists at <%= path %>', path: path, pid: pid @@ -36,7 +36,7 @@ module.exports = Promise.method(function (kbnServer, server, config) { pid: pid }); - let clean = _.once(function (code) { + const clean = _.once(function (code) { unlink(path); }); diff --git a/src/server/plugins/initialize.js b/src/server/plugins/initialize.js index 402b750fbcc03..262c2a9d0b6d2 100644 --- a/src/server/plugins/initialize.js +++ b/src/server/plugins/initialize.js @@ -7,7 +7,7 @@ module.exports = async function (kbnServer, server, config) { return []; } - let { plugins } = kbnServer; + const { plugins } = kbnServer; // extend plugin apis with additional context plugins.getPluginApis().forEach(api => { diff --git a/src/server/plugins/plugin.js b/src/server/plugins/plugin.js index bd44048bd1ad3..3c874470100a5 100644 --- a/src/server/plugins/plugin.js +++ b/src/server/plugins/plugin.js @@ -90,8 +90,8 @@ module.exports = class Plugin { } async readConfig() { - let schema = await this.getConfigSchema(Joi); - let { config } = this.kbnServer; + const schema = await this.getConfigSchema(Joi); + const { config } = this.kbnServer; config.extendSchema(this.configPrefix, schema || defaultConfigSchema); if (config.get([...toPath(this.configPrefix), 'enabled'])) { @@ -107,8 +107,8 @@ module.exports = class Plugin { } async init() { - let { id, version, kbnServer, configPrefix } = this; - let { config } = kbnServer; + const { id, version, kbnServer, configPrefix } = this; + const { config } = kbnServer; // setup the hapi register function and get on with it const asyncRegister = async (server, options) => { diff --git a/src/server/plugins/plugin_collection.js b/src/server/plugins/plugin_collection.js index 6019fd3baf60b..a7ed9689ae472 100644 --- a/src/server/plugins/plugin_collection.js +++ b/src/server/plugins/plugin_collection.js @@ -4,8 +4,8 @@ import { inspect } from 'util'; import { get, indexBy } from 'lodash'; import Collection from '../../utils/collection'; -let byIdCache = Symbol('byIdCache'); -let pluginApis = Symbol('pluginApis'); +const byIdCache = Symbol('byIdCache'); +const pluginApis = Symbol('pluginApis'); module.exports = class Plugins extends Collection { @@ -16,24 +16,24 @@ module.exports = class Plugins extends Collection { } async new(path) { - let api = new PluginApi(this.kbnServer, path); + const api = new PluginApi(this.kbnServer, path); this[pluginApis].add(api); - let output = [].concat(require(path)(api) || []); - let config = this.kbnServer.config; + const output = [].concat(require(path)(api) || []); + const config = this.kbnServer.config; if (!output.length) return; // clear the byIdCache this[byIdCache] = null; - for (let product of output) { + for (const product of output) { if (product instanceof api.Plugin) { - let plugin = product; + const plugin = product; this.add(plugin); - let enabled = await plugin.readConfig(); + const enabled = await plugin.readConfig(); if (!enabled) this.delete(plugin); continue; } diff --git a/src/server/plugins/plugin_init.js b/src/server/plugins/plugin_init.js index 8f5e9e3184478..7823b4669f42e 100644 --- a/src/server/plugins/plugin_init.js +++ b/src/server/plugins/plugin_init.js @@ -1,10 +1,10 @@ import { includes } from 'lodash'; export default async (plugins) => { - let path = []; + const path = []; const initialize = async function (id, fn) { - let plugin = plugins.byId[id]; + const plugin = plugins.byId[id]; if (includes(path, id)) { throw new Error(`circular dependencies found: "${path.concat(id).join(' -> ')}"`); @@ -12,7 +12,7 @@ export default async (plugins) => { path.push(id); - for (let reqId of plugin.requiredIds) { + for (const reqId of plugin.requiredIds) { if (!plugins.byId[reqId]) { throw new Error(`Unmet requirement "${reqId}" for plugin "${id}"`); } @@ -25,11 +25,11 @@ export default async (plugins) => { }; const collection = plugins.toArray(); - for (let {id} of collection) { + for (const {id} of collection) { await initialize(id, 'preInit'); } - for (let {id} of collection) { + for (const {id} of collection) { await initialize(id, 'init'); } }; diff --git a/src/server/plugins/scan.js b/src/server/plugins/scan.js index baa5147e44530..4ac6b3e5563ff 100644 --- a/src/server/plugins/scan.js +++ b/src/server/plugins/scan.js @@ -6,13 +6,13 @@ import { each } from 'bluebird'; import PluginCollection from './plugin_collection'; module.exports = async (kbnServer, server, config) => { - let plugins = kbnServer.plugins = new PluginCollection(kbnServer); + const plugins = kbnServer.plugins = new PluginCollection(kbnServer); - let scanDirs = [].concat(config.get('plugins.scanDirs') || []); - let pluginPaths = [].concat(config.get('plugins.paths') || []); + const scanDirs = [].concat(config.get('plugins.scanDirs') || []); + const pluginPaths = [].concat(config.get('plugins.paths') || []); - let debug = _.bindKey(server, 'log', ['plugins', 'debug']); - let warning = _.bindKey(server, 'log', ['plugins', 'warning']); + const debug = _.bindKey(server, 'log', ['plugins', 'debug']); + const warning = _.bindKey(server, 'log', ['plugins', 'warning']); // scan all scanDirs to find pluginPaths await each(scanDirs, async dir => { @@ -36,15 +36,15 @@ module.exports = async (kbnServer, server, config) => { await each(filenames, async name => { if (name[0] === '.') return; - let path = resolve(dir, name); - let stats = await fromNode(cb => stat(path, cb)); + const path = resolve(dir, name); + const stats = await fromNode(cb => stat(path, cb)); if (stats.isDirectory()) { pluginPaths.push(path); } }); }); - for (let path of pluginPaths) { + for (const path of pluginPaths) { let modulePath; try { modulePath = require.resolve(path); diff --git a/src/server/status/__tests__/server_status.js b/src/server/status/__tests__/server_status.js index 3d08250fbf81f..a1379d9373eaf 100644 --- a/src/server/status/__tests__/server_status.js +++ b/src/server/status/__tests__/server_status.js @@ -26,7 +26,7 @@ describe('ServerStatus class', function () { describe('#createForPlugin(plugin)', function () { it('should create a new status by plugin', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(status).to.be.a(Status); }); }); @@ -45,7 +45,7 @@ describe('ServerStatus class', function () { describe('#getForPluginId(plugin)', function () { it('exposes plugin status for the plugin', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(serverStatus.getForPluginId(plugin.id)).to.be(status); }); @@ -57,7 +57,7 @@ describe('ServerStatus class', function () { describe('#getState(id)', function () { it('should expose the state of a status by id', function () { - let status = serverStatus.create('someid'); + const status = serverStatus.create('someid'); status.green(); expect(serverStatus.getState('someid')).to.be('green'); }); @@ -65,7 +65,7 @@ describe('ServerStatus class', function () { describe('#getStateForPluginId(plugin)', function () { it('should expose the state of a plugin by id', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.green(); expect(serverStatus.getStateForPluginId(plugin.id)).to.be('green'); }); @@ -73,11 +73,11 @@ describe('ServerStatus class', function () { describe('#overall()', function () { it('considers each status to produce a summary', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(serverStatus.overall().state).to.be('uninitialized'); - let match = function (overall, state) { + const match = function (overall, state) { expect(overall).to.have.property('state', state.id); expect(overall).to.have.property('title', state.title); expect(overall).to.have.property('icon', state.icon); @@ -102,15 +102,15 @@ describe('ServerStatus class', function () { const pluginOne = {id: 'one', version: '1.0.0'}; const pluginTwo = {id: 'two', version: '2.0.0'}; - let service = serverStatus.create('some service'); - let p1 = serverStatus.createForPlugin(pluginOne); - let p2 = serverStatus.createForPlugin(pluginTwo); + const service = serverStatus.create('some service'); + const p1 = serverStatus.createForPlugin(pluginOne); + const p2 = serverStatus.createForPlugin(pluginTwo); service.green(); p1.yellow(); p2.red(); - let json = JSON.parse(JSON.stringify(serverStatus)); + const json = JSON.parse(JSON.stringify(serverStatus)); expect(json).to.have.property('overall'); expect(json.overall.state).to.eql(serverStatus.overall().state); expect(json.statuses).to.have.length(3); diff --git a/src/server/status/__tests__/status.js b/src/server/status/__tests__/status.js index 2dfe037791027..810a84cabe30e 100644 --- a/src/server/status/__tests__/status.js +++ b/src/server/status/__tests__/status.js @@ -19,7 +19,7 @@ describe('Status class', function () { }); it('emits change when the status is set', function (done) { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).to.be('green'); @@ -42,8 +42,8 @@ describe('Status class', function () { }); it('should only trigger the change listener when something changes', function () { - let status = serverStatus.createForPlugin(plugin); - let stub = sinon.stub(); + const status = serverStatus.createForPlugin(plugin); + const stub = sinon.stub(); status.on('change', stub); status.green('Ready'); status.green('Ready'); @@ -52,18 +52,18 @@ describe('Status class', function () { }); it('should create a JSON representation of the status', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.green('Ready'); - let json = status.toJSON(); + const json = status.toJSON(); expect(json.id).to.eql(status.id); expect(json.state).to.eql('green'); expect(json.message).to.eql('Ready'); }); it('should call on handler if status is already matched', function (done) { - let status = serverStatus.createForPlugin(plugin); - let msg = 'Test Ready'; + const status = serverStatus.createForPlugin(plugin); + const msg = 'Test Ready'; status.green(msg); status.on('green', function (prev, prevMsg) { @@ -76,8 +76,8 @@ describe('Status class', function () { }); it('should call once handler if status is already matched', function (done) { - let status = serverStatus.createForPlugin(plugin); - let msg = 'Test Ready'; + const status = serverStatus.createForPlugin(plugin); + const msg = 'Test Ready'; status.green(msg); status.once('green', function (prev, prevMsg) { @@ -91,16 +91,16 @@ describe('Status class', function () { function testState(color) { it(`should change the state to ${color} when #${color}() is called`, function () { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status[color](message); expect(status).to.have.property('state', color); expect(status).to.have.property('message', message); }); it(`should trigger the "change" listner when #${color}() is called`, function (done) { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status.on('change', function (prev, prevMsg) { expect(status.state).to.be(color); expect(status.message).to.be(message); @@ -113,8 +113,8 @@ describe('Status class', function () { }); it(`should trigger the "${color}" listner when #${color}() is called`, function (done) { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status.on(color, function (prev, prevMsg) { expect(status.state).to.be(color); expect(status.message).to.be(message); diff --git a/src/server/status/metrics.js b/src/server/status/metrics.js index 28b99011bc988..d00a8eb540d04 100644 --- a/src/server/status/metrics.js +++ b/src/server/status/metrics.js @@ -6,13 +6,13 @@ module.exports = function (kbnServer, server, config) { kbnServer.metrics = new Samples(12); server.plugins['even-better'].monitor.on('ops', function (event) { - let now = Date.now(); - let secSinceLast = (now - lastReport) / 1000; + const now = Date.now(); + const secSinceLast = (now - lastReport) / 1000; lastReport = now; - let port = config.get('server.port'); - let requests = _.get(event, ['requests', port, 'total'], 0); - let requestsPerSecond = requests / secSinceLast; + const port = config.get('server.port'); + const requests = _.get(event, ['requests', port, 'total'], 0); + const requestsPerSecond = requests / secSinceLast; kbnServer.metrics.add({ heapTotal: _.get(event, 'psmem.heapTotal'), diff --git a/src/server/status/samples.js b/src/server/status/samples.js index fd2bc4aa27c84..20164c07b7834 100644 --- a/src/server/status/samples.js +++ b/src/server/status/samples.js @@ -7,8 +7,8 @@ function Samples(max) { } Samples.prototype.add = function (sample) { - let vals = this.vals; - let length = this.length = Math.min(this.length + 1, this.max); + const vals = this.vals; + const length = this.length = Math.min(this.length + 1, this.max); _.forOwn(sample, function (val, name) { if (val == null) val = null; diff --git a/src/server/status/server_status.js b/src/server/status/server_status.js index 88c44354f2e71..ac9b4fa855e2e 100644 --- a/src/server/status/server_status.js +++ b/src/server/status/server_status.js @@ -24,7 +24,7 @@ module.exports = class ServerStatus { } each(fn) { - let self = this; + const self = this; _.forOwn(self._created, function (status, i, list) { if (status.state !== 'disabled') { fn.call(self, status, i, list); @@ -55,15 +55,15 @@ module.exports = class ServerStatus { } overall() { - let state = _(this._created) + const state = _(this._created) .map(function (status) { return states.get(status.state); }) .sortBy('severity') .pop(); - let statuses = _.where(this._created, { state: state.id }); - let since = _.get(_.sortBy(statuses, 'since'), [0, 'since']); + const statuses = _.where(this._created, { state: state.id }); + const since = _.get(_.sortBy(statuses, 'since'), [0, 'since']); return { state: state.id, @@ -83,7 +83,7 @@ module.exports = class ServerStatus { } toString() { - let overall = this.overall(); + const overall = this.overall(); return `${overall.title} – ${overall.nickname}`; } diff --git a/src/server/status/status.js b/src/server/status/status.js index 573eb041a2a6b..f8848f680b50c 100644 --- a/src/server/status/status.js +++ b/src/server/status/status.js @@ -65,8 +65,8 @@ states.all.forEach(function (state) { Status.prototype[state.id] = function (message) { if (this.state === 'disabled') return; - let previous = this.state; - let previousMsg = this.message; + const previous = this.state; + const previousMsg = this.message; this.error = null; this.message = message || state.title; diff --git a/src/test_utils/simulate_keys.js b/src/test_utils/simulate_keys.js index 8282d8e5cc9e3..b9c55f92e35a7 100644 --- a/src/test_utils/simulate_keys.js +++ b/src/test_utils/simulate_keys.js @@ -2,8 +2,8 @@ import $ from 'jquery'; import _ from 'lodash'; import Promise from 'bluebird'; import keyMap from 'ui/utils/key_map'; -let reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1)); -let KeyboardEvent = window.KeyboardEvent; +const reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1)); +const KeyboardEvent = window.KeyboardEvent; /** * Simulate keyboard events in an element. This allows testing the way that @@ -35,7 +35,7 @@ let KeyboardEvent = window.KeyboardEvent; * @async */ export default function ($el, sequence) { - let modifierState = { + const modifierState = { ctrlKey: false, shiftKey: false, altKey: false, @@ -45,7 +45,7 @@ export default function ($el, sequence) { return doList(_.clone(sequence)); function setModifier(key, state) { - let name = key + 'Key'; + const name = key + 'Key'; if (modifierState.hasOwnProperty(name)) { modifierState[name] = !!state; } @@ -91,14 +91,14 @@ export default function ($el, sequence) { } function fire(type, key, repeat) { - let keyCode = reverseKeyMap[key]; + const keyCode = reverseKeyMap[key]; if (!keyCode) throw new TypeError('invalid key "' + key + '"'); if (type === 'keydown') setModifier(key, true); if (type === 'keyup') setModifier(key, false); - let $target = _.isFunction($el) ? $el() : $el; - let $event = new $.Event(type, _.defaults({ keyCode: keyCode }, modifierState)); + const $target = _.isFunction($el) ? $el() : $el; + const $event = new $.Event(type, _.defaults({ keyCode: keyCode }, modifierState)); $target.trigger($event); } }; diff --git a/src/test_utils/stub_index_pattern.js b/src/test_utils/stub_index_pattern.js index 84f33eb229438..81f1481dd717b 100644 --- a/src/test_utils/stub_index_pattern.js +++ b/src/test_utils/stub_index_pattern.js @@ -9,10 +9,10 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import IndexPatternsFlattenHitProvider from 'ui/index_patterns/_flatten_hit'; import IndexPatternsFieldProvider from 'ui/index_patterns/_field'; export default function (Private) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let flattenHit = Private(IndexPatternsFlattenHitProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const flattenHit = Private(IndexPatternsFlattenHitProvider); - let Field = Private(IndexPatternsFieldProvider); + const Field = Private(IndexPatternsFieldProvider); function StubIndexPattern(pattern, timeField, fields) { this.id = pattern; diff --git a/src/ui/__tests__/ui_exports.js b/src/ui/__tests__/ui_exports.js index e5f6996af5fee..dcc87ccacb0a5 100644 --- a/src/ui/__tests__/ui_exports.js +++ b/src/ui/__tests__/ui_exports.js @@ -7,7 +7,7 @@ import * as kbnTestServer from '../../../test/utils/kbn_server'; describe('UiExports', function () { describe('#find()', function () { it('finds exports based on the passed export names', function () { - let uiExports = new UiExports({}); + const uiExports = new UiExports({}); uiExports.aliases.foo = ['a', 'b', 'c']; uiExports.aliases.bar = ['d', 'e', 'f']; @@ -17,7 +17,7 @@ describe('UiExports', function () { }); it('allows query types that match nothing', function () { - let uiExports = new UiExports({}); + const uiExports = new UiExports({}); uiExports.aliases.foo = ['a', 'b', 'c']; expect(uiExports.find(['foo'])).to.eql(['a', 'b', 'c']); diff --git a/src/ui/index.js b/src/ui/index.js index ada8fa2a0f069..bf4946fdb19ba 100644 --- a/src/ui/index.js +++ b/src/ui/index.js @@ -25,17 +25,17 @@ export default async (kbnServer, server, config) => { bundlerEnv.addContext('buildNum', config.get('pkg.buildNum')); uiExports.addConsumer(bundlerEnv); - for (let plugin of kbnServer.plugins) { + for (const plugin of kbnServer.plugins) { uiExports.consumePlugin(plugin); } const bundles = kbnServer.bundles = new UiBundleCollection(bundlerEnv, config.get('optimize.bundleFilter')); - for (let app of uiExports.getAllApps()) { + for (const app of uiExports.getAllApps()) { bundles.addApp(app); } - for (let gen of uiExports.getBundleProviders()) { + for (const gen of uiExports.getBundleProviders()) { const bundle = await gen(UiBundle, bundlerEnv, uiExports.getAllApps(), kbnServer.plugins); if (bundle) bundles.add(bundle); } diff --git a/src/ui/public/agg_response/geo_json/__tests__/geo_json.js b/src/ui/public/agg_response/geo_json/__tests__/geo_json.js index 94bb16a66cb98..0d7b18f02abea 100644 --- a/src/ui/public/agg_response/geo_json/__tests__/geo_json.js +++ b/src/ui/public/agg_response/geo_json/__tests__/geo_json.js @@ -17,8 +17,8 @@ describe('GeoJson Agg Response Converter', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { - let Vis = Private(VisProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const Vis = Private(VisProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); esResponse = Private(FixturesAggRespGeohashGridProvider); tabify = Private(AggResponseTabifyTabifyProvider); @@ -60,8 +60,8 @@ describe('GeoJson Agg Response Converter', function () { describe('with table ' + JSON.stringify(tableOpts), function () { it('outputs a chart', function () { - let table = makeTable(); - let chart = makeSingleChart(table); + const table = makeTable(); + const chart = makeSingleChart(table); expect(chart).to.only.have.keys( 'title', 'tooltipFormatter', @@ -78,9 +78,9 @@ describe('GeoJson Agg Response Converter', function () { }); it('outputs geohash points as features in a feature collection', function () { - let table = makeTable(); - let chart = makeSingleChart(table); - let geoJson = chart.geoJson; + const table = makeTable(); + const chart = makeSingleChart(table); + const geoJson = chart.geoJson; expect(geoJson.type).to.be('FeatureCollection'); expect(geoJson.features).to.be.an('array'); @@ -88,8 +88,8 @@ describe('GeoJson Agg Response Converter', function () { }); it('exports a bunch of properties about the geo hash grid', function () { - let geoJson = makeGeoJson(); - let props = geoJson.properties; + const geoJson = makeGeoJson(); + const props = geoJson.properties; // props expect(props).to.be.an('object'); @@ -122,7 +122,7 @@ describe('GeoJson Agg Response Converter', function () { it('should be geoJson format', function () { table.rows.forEach(function (row, i) { - let feature = chart.geoJson.features[i]; + const feature = chart.geoJson.features[i]; expect(feature).to.have.property('geometry'); expect(feature.geometry).to.be.an('object'); expect(feature).to.have.property('properties'); @@ -132,7 +132,7 @@ describe('GeoJson Agg Response Converter', function () { it('should have valid geometry data', function () { table.rows.forEach(function (row, i) { - let geometry = chart.geoJson.features[i].geometry; + const geometry = chart.geoJson.features[i].geometry; expect(geometry.type).to.be('Point'); expect(geometry).to.have.property('coordinates'); expect(geometry.coordinates).to.be.an('array'); @@ -144,8 +144,8 @@ describe('GeoJson Agg Response Converter', function () { it('should have value properties data', function () { table.rows.forEach(function (row, i) { - let props = chart.geoJson.features[i].properties; - let keys = ['value', 'geohash', 'aggConfigResult', 'rectangle', 'center']; + const props = chart.geoJson.features[i].properties; + const keys = ['value', 'geohash', 'aggConfigResult', 'rectangle', 'center']; expect(props).to.be.an('object'); expect(props).to.only.have.keys(keys); expect(props.geohash).to.be.a('string'); @@ -155,15 +155,15 @@ describe('GeoJson Agg Response Converter', function () { it('should use latLng in properties and lngLat in geometry', function () { table.rows.forEach(function (row, i) { - let geometry = chart.geoJson.features[i].geometry; - let props = chart.geoJson.features[i].properties; + const geometry = chart.geoJson.features[i].geometry; + const props = chart.geoJson.features[i].properties; expect(props.center).to.eql(geometry.coordinates.slice(0).reverse()); }); }); it('should handle both AggConfig and non-AggConfig results', function () { table.rows.forEach(function (row, i) { - let props = chart.geoJson.features[i].properties; + const props = chart.geoJson.features[i].properties; if (tableOpts.asAggConfigResults) { expect(props.aggConfigResult).to.be(row[metricColI]); expect(props.value).to.be(row[metricColI].value); diff --git a/src/ui/public/agg_response/geo_json/_tooltip_formatter.js b/src/ui/public/agg_response/geo_json/_tooltip_formatter.js index f444d5b27d0d5..23db29ff6622d 100644 --- a/src/ui/public/agg_response/geo_json/_tooltip_formatter.js +++ b/src/ui/public/agg_response/geo_json/_tooltip_formatter.js @@ -3,19 +3,19 @@ import _ from 'lodash'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function TileMapTooltipFormatter($compile, $rootScope, Private) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let $tooltipScope = $rootScope.$new(); - let $el = $('
').html(require('ui/agg_response/geo_json/_tooltip.html')); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const $tooltipScope = $rootScope.$new(); + const $el = $('
').html(require('ui/agg_response/geo_json/_tooltip.html')); $compile($el)($tooltipScope); return function tooltipFormatter(feature) { if (!feature) return ''; - let value = feature.properties.value; - let acr = feature.properties.aggConfigResult; - let vis = acr.aggConfig.vis; + const value = feature.properties.value; + const acr = feature.properties.aggConfigResult; + const vis = acr.aggConfig.vis; - let metricAgg = acr.aggConfig; + const metricAgg = acr.aggConfig; let geoFormat = _.get(vis.aggs, 'byTypeName.geohash_grid[0].format'); if (!geoFormat) geoFormat = fieldFormats.getDefaultInstance('geo_point'); diff --git a/src/ui/public/agg_response/geo_json/geo_json.js b/src/ui/public/agg_response/geo_json/geo_json.js index aac0fba222985..fe7018aee29a5 100644 --- a/src/ui/public/agg_response/geo_json/geo_json.js +++ b/src/ui/public/agg_response/geo_json/geo_json.js @@ -3,7 +3,7 @@ import rowsToFeatures from 'ui/agg_response/geo_json/rows_to_features'; import AggResponseGeoJsonTooltipFormatterProvider from 'ui/agg_response/geo_json/_tooltip_formatter'; export default function TileMapConverterFn(Private, timefilter, $compile, $rootScope) { - let tooltipFormatter = Private(AggResponseGeoJsonTooltipFormatterProvider); + const tooltipFormatter = Private(AggResponseGeoJsonTooltipFormatterProvider); return function (vis, table) { @@ -13,13 +13,13 @@ export default function TileMapConverterFn(Private, timefilter, $compile, $rootS }); } - let geoI = columnIndex('segment'); - let metricI = columnIndex('metric'); - let geoAgg = _.get(table.columns, [geoI, 'aggConfig']); - let metricAgg = _.get(table.columns, [metricI, 'aggConfig']); + const geoI = columnIndex('segment'); + const metricI = columnIndex('metric'); + const geoAgg = _.get(table.columns, [geoI, 'aggConfig']); + const metricAgg = _.get(table.columns, [metricI, 'aggConfig']); - let features = rowsToFeatures(table, geoI, metricI); - let values = features.map(function (feature) { + const features = rowsToFeatures(table, geoI, metricI); + const values = features.map(function (feature) { return feature.properties.value; }); diff --git a/src/ui/public/agg_response/geo_json/rows_to_features.js b/src/ui/public/agg_response/geo_json/rows_to_features.js index 634bfd26b5335..38e2757a50466 100644 --- a/src/ui/public/agg_response/geo_json/rows_to_features.js +++ b/src/ui/public/agg_response/geo_json/rows_to_features.js @@ -12,19 +12,19 @@ function unwrap(val) { function convertRowsToFeatures(table, geoI, metricI) { return _.transform(table.rows, function (features, row) { - let geohash = unwrap(row[geoI]); + const geohash = unwrap(row[geoI]); if (!geohash) return; // fetch latLn of northwest and southeast corners, and center point - let location = decodeGeoHash(geohash); + const location = decodeGeoHash(geohash); - let centerLatLng = [ + const centerLatLng = [ location.latitude[2], location.longitude[2] ]; // order is nw, ne, se, sw - let rectangle = [ + const rectangle = [ [location.latitude[0], location.longitude[0]], [location.latitude[0], location.longitude[1]], [location.latitude[1], location.longitude[1]], diff --git a/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js b/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js index a5e5555c81243..fcf91a9518d74 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js @@ -35,7 +35,7 @@ describe('buildHierarchicalData', function () { let results; beforeEach(function () { - let id = 1; + const id = 1; vis = new Vis(indexPattern, { type: 'pie', aggs: [ @@ -48,7 +48,7 @@ describe('buildHierarchicalData', function () { }); it('should set the slices with one child to a consistent label', function () { - let checkLabel = 'Count'; + const checkLabel = 'Count'; expect(results).to.have.property('slices'); expect(results.slices).to.have.property('children'); expect(results.slices.children).to.have.length(1); @@ -68,7 +68,7 @@ describe('buildHierarchicalData', function () { it('should set the rows', function () { let id = 1; - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -79,13 +79,13 @@ describe('buildHierarchicalData', function () { }); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); - let results = buildHierarchicalData(vis, fixtures.threeTermBuckets); + const results = buildHierarchicalData(vis, fixtures.threeTermBuckets); expect(results).to.have.property('rows'); }); it('should set the columns', function () { let id = 1; - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -96,7 +96,7 @@ describe('buildHierarchicalData', function () { }); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); - let results = buildHierarchicalData(vis, fixtures.threeTermBuckets); + const results = buildHierarchicalData(vis, fixtures.threeTermBuckets); expect(results).to.have.property('columns'); }); @@ -281,7 +281,7 @@ describe('buildHierarchicalData', function () { }); it('should set the hits attribute for the results', function () { - let errCall = Notifier.prototype.error.getCall(0); + const errCall = Notifier.prototype.error.getCall(0); expect(errCall).to.be.ok(); expect(errCall.args[0]).to.contain('not supported'); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js b/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js index d153e7d4afc34..43ec8c84bbdf4 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js @@ -4,7 +4,7 @@ import collectBranch from 'ui/agg_response/hierarchical/_collect_branch'; import expect from 'expect.js'; describe('collectBranch()', function () { let results; - let convert = function (name) { + const convert = function (name) { return 'converted:' + name; }; diff --git a/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js b/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js index f42e4442c4fd1..0a99fd9142198 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js @@ -37,7 +37,7 @@ describe('buildHierarchicalData()', function () { { type: 'terms', schema: 'segment', params: { field: 'geo.src' }} ] }); - let buckets = arrayToLinkedList(vis.aggs.bySchemaGroup.buckets); + const buckets = arrayToLinkedList(vis.aggs.bySchemaGroup.buckets); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); results = createRawData(vis, fixtures.threeTermBuckets); @@ -48,7 +48,7 @@ describe('buildHierarchicalData()', function () { expect(results.columns).to.have.length(6); _.each(results.columns, function (column) { expect(column).to.have.property('aggConfig'); - let agg = column.aggConfig; + const agg = column.aggConfig; expect(column).to.have.property('categoryName', agg.schema.name); expect(column).to.have.property('id', agg.id); expect(column).to.have.property('aggType', agg.type); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js b/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js index 8d2a45c3a1f45..59c20a8e518df 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js @@ -7,14 +7,14 @@ describe('buildHierarchicalData()', function () { it('should normalize a bucket object into an array', function () { - let bucket = { + const bucket = { buckets: { foo: { doc_count: 1 }, bar: { doc_count: 2 } } }; - let buckets = extractBuckets(bucket); + const buckets = extractBuckets(bucket); expect(buckets).to.be.an(Array); expect(buckets).to.have.length(2); expect(buckets[0]).to.have.property('key', 'foo'); @@ -24,19 +24,19 @@ describe('buildHierarchicalData()', function () { }); it('should return an empty array for undefined buckets', function () { - let buckets = extractBuckets(); + const buckets = extractBuckets(); expect(buckets).to.be.an(Array); expect(buckets).to.have.length(0); }); it('should return the bucket array', function () { - let bucket = { + const bucket = { buckets: [ { key: 'foo', doc_count: 1 }, { key: 'bar', doc_count: 2 } ] }; - let buckets = extractBuckets(bucket); + const buckets = extractBuckets(bucket); expect(buckets).to.be.an(Array); expect(buckets).to.be(bucket.buckets); }); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js b/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js index 97adf8ea4073b..d927ef738f4d7 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js @@ -42,17 +42,17 @@ describe('buildHierarchicalData()', function () { }); it('relies on metricAgg#getValue() for the size of the children', function () { - let aggData = { + const aggData = { buckets: [ { key: 'foo' }, { key: 'bar' } ] }; - let football = {}; + const football = {}; fixture.metric.getValue = _.constant(football); - let children = transform(fixture.agg, fixture.metric, aggData); + const children = transform(fixture.agg, fixture.metric, aggData); expect(children).to.be.an(Array); expect(children).to.have.length(2); expect(children[0]).to.have.property('size', football); @@ -60,7 +60,7 @@ describe('buildHierarchicalData()', function () { }); it('should create two levels of metrics', function () { - let children = transform(fixture.agg, fixture.metric, fixture.aggData); + const children = transform(fixture.agg, fixture.metric, fixture.aggData); fixture.metric.getValue = function (b) { return b.doc_count; }; expect(children).to.be.an(Array); diff --git a/src/ui/public/agg_response/hierarchical/_build_split.js b/src/ui/public/agg_response/hierarchical/_build_split.js index f4eb0fdf764ab..4cb52e7418a45 100644 --- a/src/ui/public/agg_response/hierarchical/_build_split.js +++ b/src/ui/public/agg_response/hierarchical/_build_split.js @@ -1,10 +1,10 @@ import collectKeys from 'ui/agg_response/hierarchical/_collect_keys'; import AggResponseHierarchicalTransformAggregationProvider from 'ui/agg_response/hierarchical/_transform_aggregation'; export default function biuldSplitProvider(Private) { - let transformer = Private(AggResponseHierarchicalTransformAggregationProvider); + const transformer = Private(AggResponseHierarchicalTransformAggregationProvider); return function (agg, metric, aggData) { // Ceate the split structure - let split = { label: '', slices: { children: [] } }; + const split = { label: '', slices: { children: [] } }; // Transform the aggData into splits split.slices.children = transformer(agg, metric, aggData); diff --git a/src/ui/public/agg_response/hierarchical/_collect_branch.js b/src/ui/public/agg_response/hierarchical/_collect_branch.js index 5ad6518388278..743ff469532f1 100644 --- a/src/ui/public/agg_response/hierarchical/_collect_branch.js +++ b/src/ui/public/agg_response/hierarchical/_collect_branch.js @@ -3,13 +3,13 @@ define(function () { // walk up the branch for each parent function walk(item, memo) { // record the the depth - let depth = item.depth - 1; + const depth = item.depth - 1; // Using the aggConfig determine what the field name is. If the aggConfig // doesn't exist (which means it's an _all agg) then use the level for // the field name - let col = item.aggConfig; - let field = (col && col.params && col.params.field && col.params.field.displayName) + const col = item.aggConfig; + const field = (col && col.params && col.params.field && col.params.field.displayName) || (col && col.label) || ('level ' + item.depth); diff --git a/src/ui/public/agg_response/hierarchical/_collect_keys.js b/src/ui/public/agg_response/hierarchical/_collect_keys.js index 1b9a542462c75..aa43871365ea6 100644 --- a/src/ui/public/agg_response/hierarchical/_collect_keys.js +++ b/src/ui/public/agg_response/hierarchical/_collect_keys.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function collectKeys(children) { - let nextChildren = _.pluck(children, 'children'); - let keys = _.pluck(children, 'name'); + const nextChildren = _.pluck(children, 'children'); + const keys = _.pluck(children, 'name'); return _(nextChildren) .map(collectKeys) .flattenDeep() diff --git a/src/ui/public/agg_response/hierarchical/_create_raw_data.js b/src/ui/public/agg_response/hierarchical/_create_raw_data.js index 93b9c1b519bfe..ccf9077b1994b 100644 --- a/src/ui/public/agg_response/hierarchical/_create_raw_data.js +++ b/src/ui/public/agg_response/hierarchical/_create_raw_data.js @@ -3,12 +3,12 @@ import extractBuckets from 'ui/agg_response/hierarchical/_extract_buckets'; export default function (vis, resp) { // Create the initial results structure - let results = { rows: [] }; + const results = { rows: [] }; // Create a reference to the buckets and metrics - let metrics = vis.aggs.bySchemaGroup.metrics; - let buckets = vis.aggs.bySchemaGroup.buckets; - let aggs = []; + const metrics = vis.aggs.bySchemaGroup.metrics; + const buckets = vis.aggs.bySchemaGroup.buckets; + const aggs = []; if (buckets) { _.each(buckets, function (bucket) { @@ -37,7 +37,7 @@ export default function (vis, resp) { // if there are no buckets then we need to just set the value and return if (!buckets) { - let value = resp.aggregations + const value = resp.aggregations && resp.aggregations[metrics[0].id] && resp.aggregations[metrics[0].id].value || resp.hits.total; @@ -60,7 +60,7 @@ export default function (vis, resp) { // iterate through all the buckets _.each(extractBuckets(data[agg.id], agg), function (bucket) { - let _record = _.flattenDeep([record, bucket.key]); + const _record = _.flattenDeep([record, bucket.key]); _.each(metrics, function (metric) { let value = bucket.doc_count; if (bucket[metric.id] && !_.isUndefined(bucket[metric.id].value)) { @@ -73,7 +73,7 @@ export default function (vis, resp) { // buckets. If it does then we need to keep on walking the tree. // This is where the recursion happens. if (agg._next) { - let nextBucket = bucket[agg._next.id]; + const nextBucket = bucket[agg._next.id]; if (nextBucket && nextBucket.buckets) { walkBuckets(agg._next, bucket, _record); } diff --git a/src/ui/public/agg_response/hierarchical/_extract_buckets.js b/src/ui/public/agg_response/hierarchical/_extract_buckets.js index e80f408664535..b496bece578aa 100644 --- a/src/ui/public/agg_response/hierarchical/_extract_buckets.js +++ b/src/ui/public/agg_response/hierarchical/_extract_buckets.js @@ -2,7 +2,7 @@ import _ from 'lodash'; export default function (bucket, agg) { if (bucket && _.isPlainObject(bucket.buckets)) { return _.map(bucket.buckets, function (value, key) { - let item = _.cloneDeep(value); + const item = _.cloneDeep(value); item.key = agg ? agg.getKey(value, key) : key; return item; }); diff --git a/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js b/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js index f4acab3927a57..113cf8259f4c7 100644 --- a/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js +++ b/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js @@ -3,19 +3,19 @@ import $ from 'jquery'; import collectBranch from 'ui/agg_response/hierarchical/_collect_branch'; import numeral from 'numeral'; export default function HierarchicalTooltipFormaterProvider($rootScope, $compile, $sce) { - let $tooltip = $(require('ui/agg_response/hierarchical/_tooltip.html')); - let $tooltipScope = $rootScope.$new(); + const $tooltip = $(require('ui/agg_response/hierarchical/_tooltip.html')); + const $tooltipScope = $rootScope.$new(); $compile($tooltip)($tooltipScope); return function (columns) { return function (event) { - let datum = event.datum; + const datum = event.datum; // Collect the current leaf and parents into an array of values $tooltipScope.rows = collectBranch(datum); - let metricCol = $tooltipScope.metricCol = _.find(columns, { categoryName: 'metric' }); + const metricCol = $tooltipScope.metricCol = _.find(columns, { categoryName: 'metric' }); // Map those values to what the tooltipSource.rows format. _.forEachRight($tooltipScope.rows, function (row, i, rows) { diff --git a/src/ui/public/agg_response/hierarchical/_transform_aggregation.js b/src/ui/public/agg_response/hierarchical/_transform_aggregation.js index a176f2d3e0154..fda5791ab8559 100644 --- a/src/ui/public/agg_response/hierarchical/_transform_aggregation.js +++ b/src/ui/public/agg_response/hierarchical/_transform_aggregation.js @@ -4,14 +4,14 @@ import AggConfigResult from 'ui/vis/agg_config_result'; export default function transformAggregationProvider(Private) { return function transformAggregation(agg, metric, aggData, parent) { return _.map(extractBuckets(aggData, agg), function (bucket) { - let aggConfigResult = new AggConfigResult( + const aggConfigResult = new AggConfigResult( agg, parent && parent.aggConfigResult, metric.getValue(bucket), agg.getKey(bucket) ); - let branch = { + const branch = { name: agg.fieldFormatter()(bucket.key), size: aggConfigResult.value, aggConfig: agg, @@ -27,7 +27,7 @@ export default function transformAggregationProvider(Private) { // If the next bucket exists and it has children the we need to // transform it as well. This is where the recursion happens. if (agg._next) { - let nextBucket = bucket[agg._next.id]; + const nextBucket = bucket[agg._next.id]; if (nextBucket && nextBucket.buckets) { branch.children = transformAggregation(agg._next, metric, nextBucket, branch); } diff --git a/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js b/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js index 32c782bf6622e..b851054598ba4 100644 --- a/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js +++ b/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js @@ -6,11 +6,11 @@ import AggConfigResult from 'ui/vis/agg_config_result'; import AggResponseHierarchicalBuildSplitProvider from 'ui/agg_response/hierarchical/_build_split'; import AggResponseHierarchicalHierarchicalTooltipFormatterProvider from 'ui/agg_response/hierarchical/_hierarchical_tooltip_formatter'; export default function buildHierarchicalDataProvider(Private, Notifier) { - let buildSplit = Private(AggResponseHierarchicalBuildSplitProvider); - let tooltipFormatter = Private(AggResponseHierarchicalHierarchicalTooltipFormatterProvider); + const buildSplit = Private(AggResponseHierarchicalBuildSplitProvider); + const tooltipFormatter = Private(AggResponseHierarchicalHierarchicalTooltipFormatterProvider); - let notify = new Notifier({ + const notify = new Notifier({ location: 'Pie chart response converter' }); @@ -21,19 +21,19 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { // Find the metric so it's easier to reference. // TODO: Change this to support multiple metrics. - let metric = vis.aggs.bySchemaGroup.metrics[0]; + const metric = vis.aggs.bySchemaGroup.metrics[0]; // Link each agg to the next agg. This will be // to identify the next bucket aggregation buckets = arrayToLinkedList(buckets); // Create the raw data to be used in the spy panel - let raw = createRawData(vis, resp); + const raw = createRawData(vis, resp); // If buckets is falsy then we should just return the aggs if (!buckets) { - let label = 'Count'; - let value = resp.aggregations + const label = 'Count'; + const value = resp.aggregations && resp.aggregations[metric.id] && resp.aggregations[metric.id].value || resp.hits.total; @@ -50,8 +50,8 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { }; } - let firstAgg = buckets[0]; - let aggData = resp.aggregations[firstAgg.id]; + const firstAgg = buckets[0]; + const aggData = resp.aggregations[firstAgg.id]; if (!firstAgg._next && firstAgg.schema.name === 'split') { notify.error('Splitting charts without splitting slices is not supported. Pretending that we are just splitting slices.'); @@ -59,7 +59,7 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { // start with splitting slices if (!firstAgg._next || firstAgg.schema.name === 'segment') { - let split = buildSplit(firstAgg, metric, aggData); + const split = buildSplit(firstAgg, metric, aggData); split.hits = resp.hits.total; split.raw = raw; split.tooltipFormatter = tooltipFormatter(raw.columns); @@ -67,17 +67,17 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { } // map the split aggregations into rows. - let rows = _.map(extractBuckets(aggData, firstAgg), function (bucket) { - let agg = firstAgg._next; - let split = buildSplit(agg, metric, bucket[agg.id]); + const rows = _.map(extractBuckets(aggData, firstAgg), function (bucket) { + const agg = firstAgg._next; + const split = buildSplit(agg, metric, bucket[agg.id]); // Since splits display labels we need to set it. split.label = firstAgg.fieldFormatter()(agg.getKey(bucket)); - let displayName = firstAgg.fieldDisplayName(); + const displayName = firstAgg.fieldDisplayName(); if (!_.isEmpty(displayName)) split.label += ': ' + displayName; split.tooltipFormatter = tooltipFormatter(raw.columns); - let aggConfigResult = new AggConfigResult(firstAgg, null, null, firstAgg.getKey(bucket)); + const aggConfigResult = new AggConfigResult(firstAgg, null, null, firstAgg.getKey(bucket)); split.split = { aggConfig: firstAgg, aggConfigResult: aggConfigResult, key: bucket.key }; _.each(split.slices.children, function (child) { child.aggConfigResult.$parent = aggConfigResult; @@ -85,7 +85,7 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { return split; }); - let result = { hits: resp.hits.total, raw: raw }; + const result = { hits: resp.hits.total, raw: raw }; if (firstAgg.params.row) { result.rows = rows; } else { diff --git a/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js b/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js index 4e9c563f78dbf..c07780bfbf0a2 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js +++ b/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js @@ -10,9 +10,9 @@ describe('addToSiri', function () { })); it('creates a new series the first time it sees an id', function () { - let series = new Map(); - let point = {}; - let id = 'id'; + const series = new Map(); + const point = {}; + const id = 'id'; addToSiri(series, point, id); expect(series.has(id)).to.be(true); @@ -23,13 +23,13 @@ describe('addToSiri', function () { }); it('adds points to existing series if id has been seen', function () { - let series = new Map(); - let id = 'id'; + const series = new Map(); + const id = 'id'; - let point = {}; + const point = {}; addToSiri(series, point, id); - let point2 = {}; + const point2 = {}; addToSiri(series, point2, id); expect(series.has(id)).to.be(true); @@ -41,10 +41,10 @@ describe('addToSiri', function () { }); it('allows overriding the series label', function () { - let series = new Map(); - let id = 'id'; - let label = 'label'; - let point = {}; + const series = new Map(); + const id = 'id'; + const label = 'label'; + const point = {}; addToSiri(series, point, id, label); expect(series.has(id)).to.be(true); diff --git a/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js b/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js index 501631e1c921a..1b1661186b2be 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js +++ b/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js @@ -22,8 +22,8 @@ describe('makeFakeXAspect', function () { })); it('creates an object that looks like an aspect', function () { - let vis = new Vis(indexPattern, { type: 'histogram' }); - let aspect = makeFakeXAspect(vis); + const vis = new Vis(indexPattern, { type: 'histogram' }); + const aspect = makeFakeXAspect(vis); expect(aspect) .to.have.property('i', -1) diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js b/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js index e1bf5ce07a702..ef4e7079c9e81 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js @@ -27,7 +27,7 @@ describe('getAspects', function () { let vis; let table; - let date = _.memoize(function (n) { + const date = _.memoize(function (n) { return moment().startOf('day').add(n, 'hour').valueOf(); }); @@ -50,7 +50,7 @@ describe('getAspects', function () { function init(group, x, y) { // map args to indicies that should be removed - let filter = filterByIndex([ + const filter = filterByIndex([ x > 0, x > 1, group > 0, @@ -92,7 +92,7 @@ describe('getAspects', function () { ].map(filter) }; - let aggs = vis.aggs.splice(0, vis.aggs.length); + const aggs = vis.aggs.splice(0, vis.aggs.length); filter(aggs).forEach(function (filter) { vis.aggs.push(filter); }); @@ -101,7 +101,7 @@ describe('getAspects', function () { it('produces an aspect object for each of the aspect types found in the columns', function () { init(1, 1, 1); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); validate(aspects.x, 0); validate(aspects.series, 1); validate(aspects.y, 2); @@ -110,7 +110,7 @@ describe('getAspects', function () { it('uses arrays only when there are more than one aspect of a specific type', function () { init(0, 1, 2); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); validate(aspects.x, 0); expect(aspects.series == null).to.be(true); @@ -139,7 +139,7 @@ describe('getAspects', function () { it('creates a fake x aspect if the column does not exist', function () { init(0, 0, 1); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); expect(aspects.x) .to.be.an('object') diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_point.js b/src/ui/public/agg_response/point_series/__tests__/_get_point.js index 1017a5f020cd1..30088025961d8 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_point.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_point.js @@ -7,8 +7,8 @@ describe('getPoint', function () { let getPoint; - let truthFormatted = { fieldFormatter: _.constant(_.constant(true)) }; - let identFormatted = { fieldFormatter: _.constant(_.identity) }; + const truthFormatted = { fieldFormatter: _.constant(_.constant(true)) }; + const identFormatted = { fieldFormatter: _.constant(_.identity) }; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { @@ -29,9 +29,9 @@ describe('getPoint', function () { }); it('properly unwraps and scales values', function () { - let row = [ { value: 1 }, { value: 2 }, { value: 3 } ]; - let zAspect = { i: 2 }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect, zAspect); + const row = [ { value: 1 }, { value: 2 }, { value: 3 } ]; + const zAspect = { i: 2 }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect, zAspect); expect(point) .to.have.property('x', 1) @@ -42,8 +42,8 @@ describe('getPoint', function () { }); it('ignores points with a y value of NaN', function () { - let row = [ { value: 1 }, { value: 'NaN' }]; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const row = [ { value: 1 }, { value: 'NaN' }]; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point).to.be(void 0); }); }); @@ -62,8 +62,8 @@ describe('getPoint', function () { }); it('properly unwraps and scales values', function () { - let seriesAspect = { i: 1, agg: identFormatted }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: identFormatted }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point) .to.have.property('x', 1) @@ -73,8 +73,8 @@ describe('getPoint', function () { }); it('properly formats series values', function () { - let seriesAspect = { i: 1, agg: truthFormatted }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: truthFormatted }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point) .to.have.property('x', 1) @@ -84,8 +84,8 @@ describe('getPoint', function () { }); it ('adds the aggConfig to the points', function () { - let seriesAspect = { i: 1, agg: truthFormatted}; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: truthFormatted}; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point).to.have.property('aggConfig', truthFormatted); }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_series.js b/src/ui/public/agg_response/point_series/__tests__/_get_series.js index b09fd319624fd..834df70375610 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_series.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_series.js @@ -5,7 +5,7 @@ import AggResponsePointSeriesGetSeriesProvider from 'ui/agg_response/point_serie describe('getSeries', function () { let getSeries; - let agg = { fieldFormatter: _.constant(_.identity) }; + const agg = { fieldFormatter: _.constant(_.identity) }; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { @@ -19,7 +19,7 @@ describe('getSeries', function () { } it('produces a single series with points for each row', function () { - let rows = [ + const rows = [ [1, 2, 3], [1, 2, 3], [1, 2, 3], @@ -27,7 +27,7 @@ describe('getSeries', function () { [1, 2, 3] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: 0 }, y: { i: 1 }, @@ -35,13 +35,13 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') .and.to.have.length(1); - let siri = series[0]; + const siri = series[0]; expect(siri) .to.be.an('object') .and.have.property('label', '') @@ -60,7 +60,7 @@ describe('getSeries', function () { }); it('produces multiple series if there are multiple y aspects', function () { - let rows = [ + const rows = [ [1, 2, 3], [1, 2, 3], [1, 2, 3], @@ -68,7 +68,7 @@ describe('getSeries', function () { [1, 2, 3] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: 0 }, y: [ @@ -78,7 +78,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -103,7 +103,7 @@ describe('getSeries', function () { }); it('produces multiple series if there is a series aspect', function () { - let rows = [ + const rows = [ ['0', 3], ['1', 3], ['1', 'NaN'], @@ -114,7 +114,7 @@ describe('getSeries', function () { ['1', 3] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -122,7 +122,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -147,7 +147,7 @@ describe('getSeries', function () { }); it('produces multiple series if there is a series aspect and multipl y aspects', function () { - let rows = [ + const rows = [ ['0', 3, 4], ['1', 3, 4], ['0', 3, 4], @@ -156,7 +156,7 @@ describe('getSeries', function () { ['1', 3, 4] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -167,7 +167,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -197,7 +197,7 @@ describe('getSeries', function () { }); it('produces a series list in the same order as its corresponding metric column', function () { - let rows = [ + const rows = [ ['0', 3, 4], ['1', 3, 4], ['0', 3, 4], @@ -206,7 +206,7 @@ describe('getSeries', function () { ['1', 3, 4] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -217,7 +217,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series[0]).to.have.property('label', '0: 0'); expect(series[1]).to.have.property('label', '0: 1'); expect(series[2]).to.have.property('label', '1: 0'); @@ -230,7 +230,7 @@ describe('getSeries', function () { y.i = i; }); - let series2 = getSeries(rows, chart); + const series2 = getSeries(rows, chart); expect(series2[0]).to.have.property('label', '0: 1'); expect(series2[1]).to.have.property('label', '0: 0'); expect(series2[2]).to.have.property('label', '1: 1'); diff --git a/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js b/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js index 974afab294831..9c2cfb9ef0890 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js @@ -11,7 +11,7 @@ describe('initXAxis', function () { initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); })); - let baseChart = { + const baseChart = { aspects: { x: { agg: { @@ -27,7 +27,7 @@ describe('initXAxis', function () { }; it('sets the xAxisFormatter if the agg is not ordered', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initXAxis(chart); expect(chart) .to.have.property('xAxisLabel', 'label') @@ -35,7 +35,7 @@ describe('initXAxis', function () { }); it('makes the chart ordered if the agg is ordered', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); chart.aspects.x.agg.type.ordered = true; initXAxis(chart); @@ -50,7 +50,7 @@ describe('initXAxis', function () { }); it('reads the interval param from the x agg', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); chart.aspects.x.agg.type.ordered = true; chart.aspects.x.agg.write = _.constant({ params: { interval: 10 } }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js b/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js index 97f1c98e12487..f545e3db6e0f5 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js @@ -19,7 +19,7 @@ describe('initYAxis', function () { }; } - let baseChart = { + const baseChart = { aspects: { y: [ { agg: agg(), col: { title: 'y1' } }, @@ -33,17 +33,17 @@ describe('initYAxis', function () { }; describe('with a single y aspect', function () { - let singleYBaseChart = _.cloneDeep(baseChart); + const singleYBaseChart = _.cloneDeep(baseChart); singleYBaseChart.aspects.y = singleYBaseChart.aspects.y[0]; it('sets the yAxisFormatter the the field formats convert fn', function () { - let chart = _.cloneDeep(singleYBaseChart); + const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).to.have.property('yAxisFormatter', chart.aspects.y.agg.fieldFormatter()); }); it('sets the yAxisLabel', function () { - let chart = _.cloneDeep(singleYBaseChart); + const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).to.have.property('yAxisLabel', 'y1'); }); @@ -51,7 +51,7 @@ describe('initYAxis', function () { describe('with mutliple y aspects', function () { it('sets the yAxisFormatter the the field formats convert fn for the first y aspect', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initYAxis(chart); expect(chart).to.have.property('yAxisFormatter'); @@ -61,7 +61,7 @@ describe('initYAxis', function () { }); it('does not set the yAxisLabel, it does not make sense to put multiple labels on the same axis', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initYAxis(chart); expect(chart).to.have.property('yAxisLabel', ''); }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_main.js b/src/ui/public/agg_response/point_series/__tests__/_main.js index 8eba049940350..3ba9cdced82c8 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_main.js +++ b/src/ui/public/agg_response/point_series/__tests__/_main.js @@ -25,20 +25,20 @@ describe('pointSeriesChartDataFromTable', function () { })); it('handles a table with just a count', function () { - let vis = new Vis(indexPattern, { type: 'histogram' }); - let agg = vis.aggs[0]; - let result = new AggConfigResult(vis.aggs[0], void 0, 100, 100); + const vis = new Vis(indexPattern, { type: 'histogram' }); + const agg = vis.aggs[0]; + const result = new AggConfigResult(vis.aggs[0], void 0, 100, 100); - let table = new Table(); + const table = new Table(); table.columns = [ { aggConfig: agg } ]; table.rows.push([ result ]); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(1); - let series = chartData.series[0]; + const series = chartData.series[0]; expect(series.values).to.have.length(1); expect(series.values[0]) .to.have.property('x', '_all') @@ -47,7 +47,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with x and y column', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'count', schema: 'metric' }, @@ -55,32 +55,32 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let y = { + const y = { agg: vis.aggs[0], col: { aggConfig: vis.aggs[0] }, at: function (i) { return 100 * i; } }; - let x = { + const x = { agg: vis.aggs[1], col: { aggConfig: vis.aggs[1] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let rowCount = 3; - let table = new Table(); + const rowCount = 3; + const table = new Table(); table.columns = [ x.col, y.col ]; _.times(rowCount, function (i) { - let date = new AggConfigResult(x.agg, void 0, x.at(i)); + const date = new AggConfigResult(x.agg, void 0, x.at(i)); table.rows.push([date, new AggConfigResult(y.agg, date, y.at(i))]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(1); - let series = chartData.series[0]; + const series = chartData.series[0]; expect(series.values).to.have.length(rowCount); series.values.forEach(function (point, i) { expect(point) @@ -100,7 +100,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with an x and two y aspects', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -109,40 +109,40 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let avg = { + const avg = { agg: vis.aggs[0], col: { title: 'average', aggConfig: vis.aggs[0] }, at: function (i) { return 75.444 * (i + 1); } }; - let date = { + const date = { agg: vis.aggs[1], col: { title: 'date', aggConfig: vis.aggs[1] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let max = { + const max = { agg: vis.aggs[2], col: { title: 'maximum', aggConfig: vis.aggs[2] }, at: function (i) { return 100 * (i + 1); } }; - let rowCount = 3; - let table = new Table(); + const rowCount = 3; + const table = new Table(); table.columns = [ date.col, avg.col, max.col ]; _.times(rowCount, function (i) { - let dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); - let avgResult = new AggConfigResult(avg.agg, dateResult, avg.at(i)); - let maxResult = new AggConfigResult(max.agg, dateResult, max.at(i)); + const dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); + const avgResult = new AggConfigResult(avg.agg, dateResult, avg.at(i)); + const maxResult = new AggConfigResult(max.agg, dateResult, max.at(i)); table.rows.push([dateResult, avgResult, maxResult]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(2); chartData.series.forEach(function (siri, i) { - let metric = i === 0 ? avg : max; + const metric = i === 0 ? avg : max; expect(siri).to.have.property('label', metric.col.label); expect(siri.values).to.have.length(rowCount); @@ -170,7 +170,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with an x, a series, and two y aspects', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'group', params: { field: 'extension' } }, @@ -180,53 +180,53 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let extensions = ['php', 'jpg', 'gif', 'css']; - let term = { + const extensions = ['php', 'jpg', 'gif', 'css']; + const term = { agg: vis.aggs[0], col: { title: 'extensions', aggConfig: vis.aggs[0] }, at: function (i) { return extensions[i % extensions.length]; } }; - let avg = { + const avg = { agg: vis.aggs[1], col: { title: 'average', aggConfig: vis.aggs[1] }, at: function (i) { return 75.444 * (i + 1); } }; - let date = { + const date = { agg: vis.aggs[2], col: { title: 'date', aggConfig: vis.aggs[2] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let max = { + const max = { agg: vis.aggs[3], col: { title: 'maximum', aggConfig: vis.aggs[3] }, at: function (i) { return 100 * (i + 1); } }; - let metricCount = 2; - let rowsPerSegment = 2; - let rowCount = extensions.length * rowsPerSegment; - let table = new Table(); + const metricCount = 2; + const rowsPerSegment = 2; + const rowCount = extensions.length * rowsPerSegment; + const table = new Table(); table.columns = [ date.col, term.col, avg.col, max.col ]; _.times(rowCount, function (i) { - let dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); - let termResult = new AggConfigResult(term.agg, dateResult, term.at(i)); - let avgResult = new AggConfigResult(avg.agg, termResult, avg.at(i)); - let maxResult = new AggConfigResult(max.agg, termResult, max.at(i)); + const dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); + const termResult = new AggConfigResult(term.agg, dateResult, term.at(i)); + const avgResult = new AggConfigResult(avg.agg, termResult, avg.at(i)); + const maxResult = new AggConfigResult(max.agg, termResult, max.at(i)); table.rows.push([dateResult, termResult, avgResult, maxResult]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); // one series for each extension, and then one for each metric inside expect(chartData.series).to.have.length(extensions.length * metricCount); chartData.series.forEach(function (siri, i) { // figure out the metric used to create this series - let metricAgg = siri.values[0].aggConfigResult.aggConfig; - let metric = avg.agg === metricAgg ? avg : max; + const metricAgg = siri.values[0].aggConfigResult.aggConfig; + const metric = avg.agg === metricAgg ? avg : max; expect(siri.values).to.have.length(rowsPerSegment); siri.values.forEach(function (point) { diff --git a/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js b/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js index db7763ca82772..1c3dc596f9fe5 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js @@ -6,7 +6,7 @@ import ngMock from 'ng_mock'; import AggResponsePointSeriesOrderedDateAxisProvider from 'ui/agg_response/point_series/_ordered_date_axis'; describe('orderedDateAxis', function () { - let baseArgs = { + const baseArgs = { vis: { indexPattern: { timeFieldName: '@timestamp' @@ -37,7 +37,7 @@ describe('orderedDateAxis', function () { describe('xAxisFormatter', function () { it('sets the xAxisFormatter', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(args.chart).to.have.property('xAxisFormatter'); @@ -45,10 +45,10 @@ describe('orderedDateAxis', function () { }); it('formats values using moment, and returns strings', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); - let val = '2014-08-06T12:34:01'; + const val = '2014-08-06T12:34:01'; expect(args.chart.xAxisFormatter(val)) .to.be(moment(val).format('hh:mm:ss')); }); @@ -56,7 +56,7 @@ describe('orderedDateAxis', function () { describe('ordered object', function () { it('sets date: true', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(args.chart) @@ -67,21 +67,21 @@ describe('orderedDateAxis', function () { }); it('relies on agg.buckets for the interval', function () { - let args = _.cloneDeep(baseArgs); - let spy = sinon.spy(args.chart.aspects.x.agg.buckets, 'getInterval'); + const args = _.cloneDeep(baseArgs); + const spy = sinon.spy(args.chart.aspects.x.agg.buckets, 'getInterval'); orderedDateAxis(args.vis, args.chart); expect(spy).to.have.property('callCount', 1); }); it('sets the min/max when the buckets are bounded', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(moment.isMoment(args.chart.ordered.min)).to.be(true); expect(moment.isMoment(args.chart.ordered.max)).to.be(true); }); it('does not set the min/max when the buckets are unbounded', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); args.chart.aspects.x.agg.buckets.getBounds = _.constant(); orderedDateAxis(args.vis, args.chart); expect(args.chart.ordered).to.not.have.property('min'); diff --git a/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js b/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js index 73c9e796f252b..5a54de473e578 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js +++ b/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js @@ -23,7 +23,7 @@ describe('tooltipFormatter', function () { return $row.eq(i).text().trim(); } - let baseEvent = { + const baseEvent = { datum: { aggConfigResult: { aggConfig: agg('inner'), @@ -42,20 +42,20 @@ describe('tooltipFormatter', function () { }; it('returns html based on the mouse event', function () { - let event = _.cloneDeep(baseEvent); - let $el = $(tooltipFormatter(event)); - let $rows = $el.find('tr'); + const event = _.cloneDeep(baseEvent); + const $el = $(tooltipFormatter(event)); + const $rows = $el.find('tr'); expect($rows.size()).to.be(3); - let $row1 = $rows.eq(0).find('td'); + const $row1 = $rows.eq(0).find('td'); expect(cell($row1, 0)).to.be('inner'); expect(cell($row1, 1)).to.be('(3)'); - let $row2 = $rows.eq(1).find('td'); + const $row2 = $rows.eq(1).find('td'); expect(cell($row2, 0)).to.be('middle'); expect(cell($row2, 1)).to.be('(2)'); - let $row3 = $rows.eq(2).find('td'); + const $row3 = $rows.eq(2).find('td'); expect(cell($row3, 0)).to.be('top'); expect(cell($row3, 1)).to.be('(1)'); }); diff --git a/src/ui/public/agg_response/point_series/_fake_x_aspect.js b/src/ui/public/agg_response/point_series/_fake_x_aspect.js index 5f9516a421cc2..aa4f2b6ca56ae 100644 --- a/src/ui/public/agg_response/point_series/_fake_x_aspect.js +++ b/src/ui/public/agg_response/point_series/_fake_x_aspect.js @@ -2,10 +2,10 @@ import VisAggConfigProvider from 'ui/vis/agg_config'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; export default function PointSeriesFakeXAxis(Private) { - let AggConfig = Private(VisAggConfigProvider); - let AggType = Private(AggTypesAggTypeProvider); + const AggConfig = Private(VisAggConfigProvider); + const AggType = Private(AggTypesAggTypeProvider); - let allAgg = new AggType({ + const allAgg = new AggType({ name: 'all', title: 'All docs', ordered: false, @@ -13,7 +13,7 @@ export default function PointSeriesFakeXAxis(Private) { }); return function makeFakeXAxis(vis) { - let fake = new AggConfig(vis, { + const fake = new AggConfig(vis, { type: allAgg, schema: vis.type.schemas.all.byName.segment }); diff --git a/src/ui/public/agg_response/point_series/_get_aspects.js b/src/ui/public/agg_response/point_series/_get_aspects.js index f4978de298858..648a7f752b6ce 100644 --- a/src/ui/public/agg_response/point_series/_get_aspects.js +++ b/src/ui/public/agg_response/point_series/_get_aspects.js @@ -1,9 +1,9 @@ import _ from 'lodash'; import AggResponsePointSeriesFakeXAspectProvider from 'ui/agg_response/point_series/_fake_x_aspect'; export default function PointSeriesGetAspects(Private) { - let fakeXAspect = Private(AggResponsePointSeriesFakeXAspectProvider); + const fakeXAspect = Private(AggResponsePointSeriesFakeXAspectProvider); - let map = { + const map = { segment: 'x', metric: 'y', radius: 'z', @@ -12,12 +12,12 @@ export default function PointSeriesGetAspects(Private) { }; function columnToAspect(aspects, col, i) { - let schema = col.aggConfig.schema.name; + const schema = col.aggConfig.schema.name; - let name = map[schema]; + const name = map[schema]; if (!name) throw new TypeError('unknown schema name "' + schema + '"'); - let aspect = { + const aspect = { i: i, col: col, agg: col.aggConfig @@ -36,7 +36,7 @@ export default function PointSeriesGetAspects(Private) { * may be undefined, a single aspect, or an array of aspects. */ return function getAspects(vis, table) { - let aspects = _(table.columns) + const aspects = _(table.columns) // write each column into the aspects under it's group .transform(columnToAspect, {}) // unwrap groups that only have one value, and validate groups that have more diff --git a/src/ui/public/agg_response/point_series/_get_point.js b/src/ui/public/agg_response/point_series/_get_point.js index 266ba41ce5c81..538a468ae2498 100644 --- a/src/ui/public/agg_response/point_series/_get_point.js +++ b/src/ui/public/agg_response/point_series/_get_point.js @@ -5,10 +5,10 @@ export default function PointSeriesGetPoint() { } return function getPoint(x, series, yScale, row, y, z) { - let zRow = z && row[z.i]; - let xRow = row[x.i]; + const zRow = z && row[z.i]; + const xRow = row[x.i]; - let point = { + const point = { x: unwrap(xRow, '_all'), xi: xRow && xRow.$order, y: unwrap(row[y.i]), diff --git a/src/ui/public/agg_response/point_series/_get_series.js b/src/ui/public/agg_response/point_series/_get_series.js index 817ec2712d96f..65e607d1ad7cc 100644 --- a/src/ui/public/agg_response/point_series/_get_series.js +++ b/src/ui/public/agg_response/point_series/_get_series.js @@ -2,30 +2,30 @@ import _ from 'lodash'; import AggResponsePointSeriesGetPointProvider from 'ui/agg_response/point_series/_get_point'; import AggResponsePointSeriesAddToSiriProvider from 'ui/agg_response/point_series/_add_to_siri'; export default function PointSeriesGetSeries(Private) { - let getPoint = Private(AggResponsePointSeriesGetPointProvider); - let addToSiri = Private(AggResponsePointSeriesAddToSiriProvider); + const getPoint = Private(AggResponsePointSeriesGetPointProvider); + const addToSiri = Private(AggResponsePointSeriesAddToSiriProvider); return function getSeries(rows, chart) { - let aspects = chart.aspects; - let multiY = _.isArray(aspects.y); - let yScale = chart.yScale; - let partGetPoint = _.partial(getPoint, aspects.x, aspects.series, yScale); + const aspects = chart.aspects; + const multiY = _.isArray(aspects.y); + const yScale = chart.yScale; + const partGetPoint = _.partial(getPoint, aspects.x, aspects.series, yScale); let series = _(rows) .transform(function (series, row) { if (!multiY) { - let point = partGetPoint(row, aspects.y, aspects.z); + const point = partGetPoint(row, aspects.y, aspects.z); if (point) addToSiri(series, point, point.series); return; } aspects.y.forEach(function (y) { - let point = partGetPoint(row, y, aspects.z); + const point = partGetPoint(row, y, aspects.z); if (!point) return; - let prefix = point.series ? point.series + ': ' : ''; - let seriesId = prefix + y.agg.id; - let seriesLabel = prefix + y.col.title; + const prefix = point.series ? point.series + ': ' : ''; + const seriesId = prefix + y.agg.id; + const seriesLabel = prefix + y.col.title; addToSiri(series, point, seriesId, seriesLabel); }); @@ -36,11 +36,11 @@ export default function PointSeriesGetSeries(Private) { if (multiY) { series = _.sortBy(series, function (siri) { - let firstVal = siri.values[0]; + const firstVal = siri.values[0]; let y; if (firstVal) { - let agg = firstVal.aggConfigResult.aggConfig; + const agg = firstVal.aggConfigResult.aggConfig; y = _.find(aspects.y, function (y) { return y.agg === agg; }); diff --git a/src/ui/public/agg_response/point_series/_init_x_axis.js b/src/ui/public/agg_response/point_series/_init_x_axis.js index 2a3584c3834f7..b4e271d33f08c 100644 --- a/src/ui/public/agg_response/point_series/_init_x_axis.js +++ b/src/ui/public/agg_response/point_series/_init_x_axis.js @@ -1,14 +1,14 @@ define(function () { return function PointSeriesInitX() { return function initXAxis(chart) { - let x = chart.aspects.x; + const x = chart.aspects.x; chart.xAxisFormatter = x.agg ? x.agg.fieldFormatter() : String; chart.xAxisLabel = x.col.title; if (!x.agg || !x.agg.type.ordered) return; chart.ordered = {}; - let xAggOutput = x.agg.write(); + const xAggOutput = x.agg.write(); if (xAggOutput.params.interval) { chart.ordered.interval = xAggOutput.params.interval; } diff --git a/src/ui/public/agg_response/point_series/_init_y_axis.js b/src/ui/public/agg_response/point_series/_init_y_axis.js index edd3060fc85c2..2f2d2039deb19 100644 --- a/src/ui/public/agg_response/point_series/_init_y_axis.js +++ b/src/ui/public/agg_response/point_series/_init_y_axis.js @@ -2,8 +2,8 @@ import _ from 'lodash'; export default function PointSeriesInitYAxis() { return function initYAxis(chart) { - let y = chart.aspects.y; - let x = chart.aspects.x; + const y = chart.aspects.y; + const x = chart.aspects.x; if (_.isArray(y)) { // TODO: vis option should allow choosing this format @@ -14,7 +14,7 @@ export default function PointSeriesInitYAxis() { chart.yAxisLabel = y.col.title; } - let xAggOutput = x.agg.write(); + const xAggOutput = x.agg.write(); chart.yScale = xAggOutput.metricScale || null; }; }; diff --git a/src/ui/public/agg_response/point_series/_ordered_date_axis.js b/src/ui/public/agg_response/point_series/_ordered_date_axis.js index 08b1d962252f2..1a72b4d6e6e3a 100644 --- a/src/ui/public/agg_response/point_series/_ordered_date_axis.js +++ b/src/ui/public/agg_response/point_series/_ordered_date_axis.js @@ -2,9 +2,9 @@ import moment from 'moment'; export default function PointSeriesOrderedDateAxis(timefilter) { return function orderedDateAxis(vis, chart) { - let xAgg = chart.aspects.x.agg; - let buckets = xAgg.buckets; - let format = buckets.getScaledDateFormat(); + const xAgg = chart.aspects.x.agg; + const buckets = xAgg.buckets; + const format = buckets.getScaledDateFormat(); chart.xAxisFormatter = function (val) { return moment(val).format(format); @@ -15,8 +15,8 @@ export default function PointSeriesOrderedDateAxis(timefilter) { interval: buckets.getInterval(), }; - let axisOnTimeField = xAgg.fieldIsTimeField(); - let bounds = buckets.getBounds(); + const axisOnTimeField = xAgg.fieldIsTimeField(); + const bounds = buckets.getBounds(); if (bounds && axisOnTimeField) { chart.ordered.min = bounds.min; chart.ordered.max = bounds.max; diff --git a/src/ui/public/agg_response/point_series/_tooltip_formatter.js b/src/ui/public/agg_response/point_series/_tooltip_formatter.js index 715d692127d1e..c6e12fd7bf5b8 100644 --- a/src/ui/public/agg_response/point_series/_tooltip_formatter.js +++ b/src/ui/public/agg_response/point_series/_tooltip_formatter.js @@ -1,22 +1,22 @@ import $ from 'jquery'; export default function PointSeriesTooltipFormatter($compile, $rootScope) { - let $tooltipScope = $rootScope.$new(); - let $tooltip = $(require('ui/agg_response/point_series/_tooltip.html')); + const $tooltipScope = $rootScope.$new(); + const $tooltip = $(require('ui/agg_response/point_series/_tooltip.html')); $compile($tooltip)($tooltipScope); return function tooltipFormatter(event) { - let datum = event.datum; + const datum = event.datum; if (!datum || !datum.aggConfigResult) return ''; - let details = $tooltipScope.details = []; + const details = $tooltipScope.details = []; let result = { $parent: datum.aggConfigResult }; function addDetail(result) { - let agg = result.aggConfig; - let value = result.value; + const agg = result.aggConfig; + const value = result.value; - let detail = { + const detail = { value: agg.fieldFormatter()(value), label: agg.makeLabel() }; diff --git a/src/ui/public/agg_response/point_series/point_series.js b/src/ui/public/agg_response/point_series/point_series.js index 0a2ccd90729c4..eb057200db47d 100644 --- a/src/ui/public/agg_response/point_series/point_series.js +++ b/src/ui/public/agg_response/point_series/point_series.js @@ -7,23 +7,23 @@ import AggResponsePointSeriesOrderedDateAxisProvider from 'ui/agg_response/point import AggResponsePointSeriesTooltipFormatterProvider from 'ui/agg_response/point_series/_tooltip_formatter'; export default function PointSeriesProvider(Private) { - let getSeries = Private(AggResponsePointSeriesGetSeriesProvider); - let getAspects = Private(AggResponsePointSeriesGetAspectsProvider); - let initYAxis = Private(AggResponsePointSeriesInitYAxisProvider); - let initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); - let setupOrderedDateXAxis = Private(AggResponsePointSeriesOrderedDateAxisProvider); - let tooltipFormatter = Private(AggResponsePointSeriesTooltipFormatterProvider); + const getSeries = Private(AggResponsePointSeriesGetSeriesProvider); + const getAspects = Private(AggResponsePointSeriesGetAspectsProvider); + const initYAxis = Private(AggResponsePointSeriesInitYAxisProvider); + const initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); + const setupOrderedDateXAxis = Private(AggResponsePointSeriesOrderedDateAxisProvider); + const tooltipFormatter = Private(AggResponsePointSeriesTooltipFormatterProvider); return function pointSeriesChartDataFromTable(vis, table) { - let chart = {}; - let aspects = chart.aspects = getAspects(vis, table); + const chart = {}; + const aspects = chart.aspects = getAspects(vis, table); chart.tooltipFormatter = tooltipFormatter; initXAxis(chart); initYAxis(chart); - let datedX = aspects.x.agg.type.ordered && aspects.x.agg.type.ordered.date; + const datedX = aspects.x.agg.type.ordered && aspects.x.agg.type.ordered.date; if (datedX) { setupOrderedDateXAxis(vis, chart); } diff --git a/src/ui/public/agg_response/tabify/__tests__/_buckets.js b/src/ui/public/agg_response/tabify/__tests__/_buckets.js index e2ecc8e75d55d..ef34f4d3cafbd 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_buckets.js +++ b/src/ui/public/agg_response/tabify/__tests__/_buckets.js @@ -12,13 +12,13 @@ describe('Buckets wrapper', function () { function test(aggResp, count, keys) { it('reads the length', function () { - let buckets = new Buckets(aggResp); + const buckets = new Buckets(aggResp); expect(buckets).to.have.length(count); }); it('itterates properly, passing in the key', function () { - let buckets = new Buckets(aggResp); - let keysSent = []; + const buckets = new Buckets(aggResp); + const keysSent = []; buckets.forEach(function (bucket, key) { keysSent.push(key); }); @@ -29,7 +29,7 @@ describe('Buckets wrapper', function () { } describe('with object style buckets', function () { - let aggResp = { + const aggResp = { buckets: { '0-100': {}, '100-200': {}, @@ -37,14 +37,14 @@ describe('Buckets wrapper', function () { } }; - let count = 3; - let keys = ['0-100', '100-200', '200-300']; + const count = 3; + const keys = ['0-100', '100-200', '200-300']; test(aggResp, count, keys); }); describe('with array style buckets', function () { - let aggResp = { + const aggResp = { buckets: [ { key: '0-100', value: {} }, { key: '100-200', value: {} }, @@ -52,8 +52,8 @@ describe('Buckets wrapper', function () { ] }; - let count = 3; - let keys = ['0-100', '100-200', '200-300']; + const count = 3; + const keys = ['0-100', '100-200', '200-300']; test(aggResp, count, keys); }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_get_columns.js b/src/ui/public/agg_response/tabify/__tests__/_get_columns.js index d8db8717c2dc0..e0b315d757bb3 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_get_columns.js +++ b/src/ui/public/agg_response/tabify/__tests__/_get_columns.js @@ -16,11 +16,11 @@ describe('get columns', function () { })); it('should inject a count metric if no aggs exist', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie' }); while (vis.aggs.length) vis.aggs.pop(); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(1); expect(columns[0]).to.have.property('aggConfig'); @@ -28,14 +28,14 @@ describe('get columns', function () { }); it('should inject a count metric if only buckets exist', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } } ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(2); expect(columns[1]).to.have.property('aggConfig'); @@ -43,7 +43,7 @@ describe('get columns', function () { }); it('should inject the metric after each bucket if the vis is hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -53,7 +53,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(8); columns.forEach(function (column, i) { @@ -63,7 +63,7 @@ describe('get columns', function () { }); it('should inject the multiple metrics after each bucket if the vis is hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -75,7 +75,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); function checkColumns(column, i) { expect(column).to.have.property('aggConfig'); @@ -94,13 +94,13 @@ describe('get columns', function () { expect(columns).to.have.length(12); for (let i = 0; i < columns.length; i += 3) { - let counts = { buckets: 0, metrics: 0 }; + const counts = { buckets: 0, metrics: 0 }; columns.slice(i, i + 3).forEach(checkColumns); } }); it('should put all metrics at the end of the columns if the vis is not hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -112,7 +112,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(6); // sum should be last diff --git a/src/ui/public/agg_response/tabify/__tests__/_integration.js b/src/ui/public/agg_response/tabify/__tests__/_integration.js index ea5d6096219d6..528a732f29d09 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_integration.js +++ b/src/ui/public/agg_response/tabify/__tests__/_integration.js @@ -26,13 +26,13 @@ describe('tabifyAggResponse Integration', function () { } it('transforms a simple response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); normalizeIds(vis); - let resp = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); + const resp = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); expect(resp).to.not.have.property('tables'); expect(resp).to.have.property('rows').and.property('columns'); @@ -81,7 +81,7 @@ describe('tabifyAggResponse Integration', function () { function expectRootGroup(rootTableGroup, expectInnerTables) { expect(rootTableGroup).to.have.property('tables'); - let tables = rootTableGroup.tables; + const tables = rootTableGroup.tables; expect(tables).to.be.an('array').and.have.length(3); expectExtensionSplit(tables[0], 'png', expectInnerTables); expectExtensionSplit(tables[1], 'css', expectInnerTables); @@ -155,7 +155,7 @@ describe('tabifyAggResponse Integration', function () { // only complete rows, and only put the metrics at the end. vis.isHierarchical = _.constant(false); - let tabbed = tabifyAggResponse(vis, esResp); + const tabbed = tabifyAggResponse(vis, esResp); expectRootGroup(tabbed, function expectTable(table, splitKey) { expectColumns(table, [src, os, avg]); @@ -181,7 +181,7 @@ describe('tabifyAggResponse Integration', function () { // the existing bucket and it's metric vis.isHierarchical = _.constant(true); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { partialRows: true }); @@ -215,7 +215,7 @@ describe('tabifyAggResponse Integration', function () { // the end vis.isHierarchical = _.constant(true); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { partialRows: true, minimalColumns: true }); @@ -247,7 +247,7 @@ describe('tabifyAggResponse Integration', function () { // create metric columns after each bucket vis.isHierarchical = _.constant(false); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { minimalColumns: false }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_response_writer.js b/src/ui/public/agg_response/tabify/__tests__/_response_writer.js index 5f81ef8190d68..48275dbbf7679 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_response_writer.js +++ b/src/ui/public/agg_response/tabify/__tests__/_response_writer.js @@ -42,15 +42,15 @@ describe('ResponseWriter class', function () { defineSetup(true); it('gets the columns for the vis', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(getColumns).to.have.property('callCount', 1); expect(getColumns.firstCall.args[0]).to.be(vis); }); it('collects the aggConfigs from each column in aggStack', function () { - let aggs = [ + const aggs = [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, { type: 'terms', schema: 'segment', params: { field: 'extension' } }, { type: 'avg', schema: 'metric', params: { field: '@timestamp' } } @@ -60,12 +60,12 @@ describe('ResponseWriter class', function () { return { aggConfig: agg }; })); - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: aggs }); - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); expect(writer.aggStack).to.be.an('array'); expect(writer.aggStack).to.have.length(aggs.length); writer.aggStack.forEach(function (agg, i) { @@ -74,40 +74,40 @@ describe('ResponseWriter class', function () { }); it('sets canSplit=true by default', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer).to.have.property('canSplit', true); }); it('sets canSplit=false when config says to', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis, { canSplit: false }); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis, { canSplit: false }); expect(writer).to.have.property('canSplit', false); }); describe('sets partialRows', function () { it('to the value of the config if set', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let partial = Boolean(Math.round(Math.random())); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const partial = Boolean(Math.round(Math.random())); - let writer = new ResponseWriter(vis, { partialRows: partial }); + const writer = new ResponseWriter(vis, { partialRows: partial }); expect(writer).to.have.property('partialRows', partial); }); it('to the value of vis.isHierarchical if no config', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let hierarchical = Boolean(Math.round(Math.random())); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const hierarchical = Boolean(Math.round(Math.random())); sinon.stub(vis, 'isHierarchical').returns(hierarchical); - let writer = new ResponseWriter(vis, {}); + const writer = new ResponseWriter(vis, {}); expect(writer).to.have.property('partialRows', hierarchical); }); }); it('starts off with a root TableGroup', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); expect(writer.root).to.be.a(TableGroup); expect(writer.splitStack).to.be.an('array'); expect(writer.splitStack).to.have.length(1); @@ -120,29 +120,29 @@ describe('ResponseWriter class', function () { describe('#response()', function () { it('returns the root TableGroup if splitting', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer.response()).to.be(writer.root); }); it('returns the first table if not splitting', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis, { canSplit: false }); - let table = writer._table(); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis, { canSplit: false }); + const table = writer._table(); expect(writer.response()).to.be(table); }); it('adds columns to all of the tables', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', params: { field: '_type' }, schema: 'split' }, { type: 'count', schema: 'metric' } ] }); - let buckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let writer = new ResponseWriter(vis); - let tables = []; + const buckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const writer = new ResponseWriter(vis); + const tables = []; writer.split(vis.aggs[0], buckets, function () { writer.cell(vis.aggs[1], 100, function () { @@ -154,11 +154,11 @@ describe('ResponseWriter class', function () { expect(table.columns == null).to.be(true); }); - let resp = writer.response(); + const resp = writer.response(); expect(resp).to.be.a(TableGroup); expect(resp.tables).to.have.length(2); - let nginx = resp.tables.shift(); + const nginx = resp.tables.shift(); expect(nginx).to.have.property('aggConfig', vis.aggs[0]); expect(nginx).to.have.property('key', 'nginx'); expect(nginx.tables).to.have.length(1); @@ -166,7 +166,7 @@ describe('ResponseWriter class', function () { expect(_.contains(tables, table)).to.be(true); }); - let apache = resp.tables.shift(); + const apache = resp.tables.shift(); expect(apache).to.have.property('aggConfig', vis.aggs[0]); expect(apache).to.have.property('key', 'apache'); expect(apache.tables).to.have.length(1); @@ -184,16 +184,16 @@ describe('ResponseWriter class', function () { describe('#split()', function () { it('with break if the user has specified that splitting is to be disabled', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'split', params: { field: '_type' } }, { type: 'count', schema: 'metric' } ] }); - let agg = vis.aggs.bySchemaName.split[0]; - let buckets = new Buckets({ buckets: [ { key: 'apache' } ]}); - let writer = new ResponseWriter(vis, { canSplit: false }); + const agg = vis.aggs.bySchemaName.split[0]; + const buckets = new Buckets({ buckets: [ { key: 'apache' } ]}); + const writer = new ResponseWriter(vis, { canSplit: false }); expect(function () { writer.split(agg, buckets, _.noop); @@ -201,7 +201,7 @@ describe('ResponseWriter class', function () { }); it('forks the acrStack and rewrites the parents', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', params: { field: 'extension' }, schema: 'segment' }, @@ -211,10 +211,10 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis, { asAggConfigResults: true }); - let extensions = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); - let types = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let os = new Buckets({ buckets: [ { key: 'window' }, { key: 'osx' } ] }); + const writer = new ResponseWriter(vis, { asAggConfigResults: true }); + const extensions = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); + const types = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const os = new Buckets({ buckets: [ { key: 'window' }, { key: 'osx' } ] }); extensions.forEach(function (b, extension) { writer.cell(vis.aggs[0], extension, function () { @@ -230,11 +230,11 @@ describe('ResponseWriter class', function () { }); }); - let tables = _.flattenDeep(_.pluck(writer.response().tables, 'tables')); + const tables = _.flattenDeep(_.pluck(writer.response().tables, 'tables')); expect(tables.length).to.be(types.length); // collect the far left acr from each table - let leftAcrs = _.pluck(tables, 'rows[0][0]'); + const leftAcrs = _.pluck(tables, 'rows[0][0]'); leftAcrs.forEach(function (acr, i, acrs) { expect(acr.aggConfig).to.be(vis.aggs[0]); @@ -243,7 +243,7 @@ describe('ResponseWriter class', function () { // for all but the last acr, compare to the next if (i + 1 >= acrs.length) return; - let acr2 = leftAcrs[i + 1]; + const acr2 = leftAcrs[i + 1]; expect(acr.key).to.be(acr2.key); expect(acr.value).to.be(acr2.value); @@ -258,8 +258,8 @@ describe('ResponseWriter class', function () { describe('#cell()', function () { it('logs a cell in the ResponseWriters row buffer, calls the block arg, then removes the value from the buffer', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer.rowBuffer).to.have.length(0); writer.cell({}, 500, function () { @@ -272,10 +272,10 @@ describe('ResponseWriter class', function () { describe('#row()', function () { it('writes the ResponseWriters internal rowBuffer into a table', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); - let table = writer._table(); + const table = writer._table(); writer.cell({}, 1, function () { writer.cell({}, 2, function () { writer.cell({}, 3, function () { @@ -289,7 +289,7 @@ describe('ResponseWriter class', function () { }); it('always writes to the table group at the top of the split stack', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'split', params: { field: '_type' } }, @@ -298,20 +298,20 @@ describe('ResponseWriter class', function () { { type: 'count', schema: 'metric' } ] }); - let splits = vis.aggs.bySchemaName.split; + const splits = vis.aggs.bySchemaName.split; - let type = splits[0]; - let typeBuckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const type = splits[0]; + const typeBuckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let ext = splits[1]; - let extBuckets = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); + const ext = splits[1]; + const extBuckets = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); - let os = splits[2]; - let osBuckets = new Buckets({ buckets: [ { key: 'windows' }, { key: 'mac' } ] }); + const os = splits[2]; + const osBuckets = new Buckets({ buckets: [ { key: 'windows' }, { key: 'mac' } ] }); - let count = vis.aggs[3]; + const count = vis.aggs[3]; - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); writer.split(type, typeBuckets, function () { writer.split(ext, extBuckets, function () { writer.split(os, osBuckets, function (bucket, key) { @@ -322,7 +322,7 @@ describe('ResponseWriter class', function () { }); }); - let resp = writer.response(); + const resp = writer.response(); let sum = 0; let tables = 0; (function recurse(t) { @@ -347,7 +347,7 @@ describe('ResponseWriter class', function () { }); it('writes partial rows for hierarchical vis', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' }}, @@ -355,8 +355,8 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis); - let table = writer._table(); + const writer = new ResponseWriter(vis); + const table = writer._table(); writer.cell(vis.aggs[0], 'apache', function () { writer.row(); }); @@ -366,7 +366,7 @@ describe('ResponseWriter class', function () { }); it('skips partial rows for non-hierarchical vis', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' }}, @@ -374,8 +374,8 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis); - let table = writer._table(); + const writer = new ResponseWriter(vis); + const table = writer._table(); writer.cell(vis.aggs[0], 'apache', function () { writer.row(); }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_table.js b/src/ui/public/agg_response/tabify/__tests__/_table.js index 1e4a869bcc229..ef54028aa5df6 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_table.js +++ b/src/ui/public/agg_response/tabify/__tests__/_table.js @@ -12,16 +12,16 @@ describe('Table class', function () { })); it('exposes rows array, but not the columns', function () { - let table = new Table(); + const table = new Table(); expect(table.rows).to.be.an('array'); expect(table.columns == null).to.be.ok(); }); describe('#aggConfig', function () { it('accepts a column from the table and returns its agg config', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: football }; @@ -30,7 +30,7 @@ describe('Table class', function () { it('throws a TypeError if the column is malformed', function () { expect(function () { - let notAColumn = {}; + const notAColumn = {}; (new Table()).aggConfig(notAColumn); }).to.throwException(TypeError); }); @@ -38,12 +38,12 @@ describe('Table class', function () { describe('#title', function () { it('returns nothing if the table is not part of a table group', function () { - let table = new Table(); + const table = new Table(); expect(table.title()).to.be(''); }); it('returns the title of the TableGroup if the table is part of one', function () { - let table = new Table(); + const table = new Table(); table.$parent = { title: 'TableGroup Title', tables: [table] @@ -55,9 +55,9 @@ describe('Table class', function () { describe('#field', function () { it('calls the columns aggConfig#field() method', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: { field: _.constant(football) } @@ -69,9 +69,9 @@ describe('Table class', function () { describe('#fieldFormatter', function () { it('calls the columns aggConfig#fieldFormatter() method', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: { fieldFormatter: _.constant(football) } diff --git a/src/ui/public/agg_response/tabify/__tests__/_table_group.js b/src/ui/public/agg_response/tabify/__tests__/_table_group.js index 5455caa143f34..d880596d45852 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_table_group.js +++ b/src/ui/public/agg_response/tabify/__tests__/_table_group.js @@ -10,7 +10,7 @@ describe('Table Group class', function () { })); it('exposes tables array and empty aggConfig, key and title', function () { - let tableGroup = new TableGroup(); + const tableGroup = new TableGroup(); expect(tableGroup.tables).to.be.an('array'); expect(tableGroup.aggConfig).to.be(null); expect(tableGroup.key).to.be(null); diff --git a/src/ui/public/agg_response/tabify/_buckets.js b/src/ui/public/agg_response/tabify/_buckets.js index 7d05c83a882b1..001147c460675 100644 --- a/src/ui/public/agg_response/tabify/_buckets.js +++ b/src/ui/public/agg_response/tabify/_buckets.js @@ -15,7 +15,7 @@ export default function AggResponseBucketsProvider() { } Buckets.prototype.forEach = function (fn) { - let buckets = this.buckets; + const buckets = this.buckets; if (this.objectMode) { this._keys.forEach(function (key) { diff --git a/src/ui/public/agg_response/tabify/_get_columns.js b/src/ui/public/agg_response/tabify/_get_columns.js index b9268891cadc3..a4f2e9041ebd9 100644 --- a/src/ui/public/agg_response/tabify/_get_columns.js +++ b/src/ui/public/agg_response/tabify/_get_columns.js @@ -1,10 +1,10 @@ import _ from 'lodash'; import VisAggConfigProvider from 'ui/vis/agg_config'; export default function GetColumnsProvider(Private) { - let AggConfig = Private(VisAggConfigProvider); + const AggConfig = Private(VisAggConfigProvider); return function getColumns(vis, minimal) { - let aggs = vis.aggs.getResponseAggs(); + const aggs = vis.aggs.getResponseAggs(); if (minimal == null) minimal = !vis.isHierarchical(); @@ -23,10 +23,10 @@ export default function GetColumnsProvider(Private) { } // supposed to be bucket,...metrics,bucket,...metrics - let columns = []; + const columns = []; // seperate the metrics - let grouped = _.groupBy(aggs, function (agg) { + const grouped = _.groupBy(aggs, function (agg) { return agg.schema.group; }); diff --git a/src/ui/public/agg_response/tabify/_response_writer.js b/src/ui/public/agg_response/tabify/_response_writer.js index 53f1ee01782ac..d023392815a7f 100644 --- a/src/ui/public/agg_response/tabify/_response_writer.js +++ b/src/ui/public/agg_response/tabify/_response_writer.js @@ -4,9 +4,9 @@ import AggResponseTabifyTableProvider from 'ui/agg_response/tabify/_table'; import AggResponseTabifyTableGroupProvider from 'ui/agg_response/tabify/_table_group'; import AggResponseTabifyGetColumnsProvider from 'ui/agg_response/tabify/_get_columns'; export default function TabbedAggResponseWriterProvider(Private) { - let Table = Private(AggResponseTabifyTableProvider); - let TableGroup = Private(AggResponseTabifyTableGroupProvider); - let getColumns = Private(AggResponseTabifyGetColumnsProvider); + const Table = Private(AggResponseTabifyTableProvider); + const TableGroup = Private(AggResponseTabifyTableGroupProvider); + const getColumns = Private(AggResponseTabifyGetColumnsProvider); _.class(SplitAcr).inherits(AggConfigResult); @@ -25,7 +25,7 @@ export default function TabbedAggResponseWriterProvider(Private) { this.opts = opts || {}; this.rowBuffer = []; - let visIsHier = vis.isHierarchical(); + const visIsHier = vis.isHierarchical(); // do the options allow for splitting? we will only split if true and // tabify calls the split method. @@ -67,9 +67,9 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {Table/TableGroup} table - the created table */ TabbedAggResponseWriter.prototype._table = function (group, agg, key) { - let Class = (group) ? TableGroup : Table; - let table = new Class(); - let parent = this.splitStack[0]; + const Class = (group) ? TableGroup : Table; + const table = new Class(); + const parent = this.splitStack[0]; if (group) { table.aggConfig = agg; @@ -95,7 +95,7 @@ export default function TabbedAggResponseWriterProvider(Private) { * @param {function} block - a function to execute for each sub bucket */ TabbedAggResponseWriter.prototype.split = function (agg, buckets, block) { - let self = this; + const self = this; if (!self.canSplit) { throw new Error('attempted to split when splitting is disabled'); @@ -127,7 +127,7 @@ export default function TabbedAggResponseWriterProvider(Private) { }; TabbedAggResponseWriter.prototype._removeAggFromColumns = function (agg) { - let i = _.findIndex(this.columns, function (col) { + const i = _.findIndex(this.columns, function (col) { return col.aggConfig === agg; }); @@ -140,8 +140,8 @@ export default function TabbedAggResponseWriterProvider(Private) { // hierarchical vis creats additional columns for each bucket // we will remove those too - let mCol = this.columns.splice(i, 1).pop(); - let mI = _.findIndex(this.aggStack, function (agg) { + const mCol = this.columns.splice(i, 1).pop(); + const mI = _.findIndex(this.aggStack, function (agg) { return agg === mCol.aggConfig; }); @@ -160,8 +160,8 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {SplitAcr} - the AggConfigResult created for the split bucket */ TabbedAggResponseWriter.prototype._injectParentSplit = function (agg, key) { - let oldList = this.acrStack; - let newList = this.acrStack = []; + const oldList = this.acrStack; + const newList = this.acrStack = []; // walk from right to left through the old stack // and move things to the new stack @@ -175,7 +175,7 @@ export default function TabbedAggResponseWriterProvider(Private) { // walk from right to left, emptying the previous list while (oldList.length) { - let acr = oldList.pop(); + const acr = oldList.pop(); // ignore other splits if (acr instanceof SplitAcr) { @@ -189,11 +189,11 @@ export default function TabbedAggResponseWriterProvider(Private) { newList.unshift(injected); } - let newAcr = new AggConfigResult(acr.aggConfig, newList[0], acr.value, acr.aggConfig.getKey(acr)); + const newAcr = new AggConfigResult(acr.aggConfig, newList[0], acr.value, acr.aggConfig.getKey(acr)); newList.unshift(newAcr); // and replace the acr in the row buffer if its there - let rowI = this.rowBuffer.indexOf(acr); + const rowI = this.rowBuffer.indexOf(acr); if (rowI > -1) { this.rowBuffer[rowI] = newAcr; } @@ -215,7 +215,7 @@ export default function TabbedAggResponseWriterProvider(Private) { value = new AggConfigResult(agg, this.acrStack[0], value, value); } - let staskResult = this.asAggConfigResults && value.type === 'bucket'; + const staskResult = this.asAggConfigResults && value.type === 'bucket'; this.rowBuffer.push(value); if (staskResult) this.acrStack.unshift(value); @@ -237,14 +237,14 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {undefined} */ TabbedAggResponseWriter.prototype.row = function (buffer) { - let cells = buffer || this.rowBuffer.slice(0); + const cells = buffer || this.rowBuffer.slice(0); if (!this.partialRows && cells.length < this.columns.length) { return; } - let split = this.splitStack[0]; - let table = split.tables[0] || this._table(false); + const split = this.splitStack[0]; + const table = split.tables[0] || this._table(false); while (cells.length < this.columns.length) cells.push(''); table.rows.push(cells); @@ -257,7 +257,7 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {object} - the final table-tree */ TabbedAggResponseWriter.prototype.response = function () { - let columns = this.columns; + const columns = this.columns; // give the columns some metadata columns.map(function (col) { @@ -272,7 +272,7 @@ export default function TabbedAggResponseWriterProvider(Private) { if (this.canSplit) return this.root; - let table = this.root.tables[0]; + const table = this.root.tables[0]; if (!table) return; delete table.$parent; diff --git a/src/ui/public/agg_response/tabify/tabify.js b/src/ui/public/agg_response/tabify/tabify.js index 722a1a12b8032..36296bf2f7377 100644 --- a/src/ui/public/agg_response/tabify/tabify.js +++ b/src/ui/public/agg_response/tabify/tabify.js @@ -4,15 +4,15 @@ import AggResponseTabifyResponseWriterProvider from 'ui/agg_response/tabify/_res import AggResponseTabifyBucketsProvider from 'ui/agg_response/tabify/_buckets'; export default function tabifyAggResponseProvider(Private, Notifier) { - let AggConfig = Private(VisAggConfigProvider); - let TabbedAggResponseWriter = Private(AggResponseTabifyResponseWriterProvider); - let Buckets = Private(AggResponseTabifyBucketsProvider); - let notify = new Notifier({ location: 'agg_response/tabify'}); + const AggConfig = Private(VisAggConfigProvider); + const TabbedAggResponseWriter = Private(AggResponseTabifyResponseWriterProvider); + const Buckets = Private(AggResponseTabifyBucketsProvider); + const notify = new Notifier({ location: 'agg_response/tabify'}); function tabifyAggResponse(vis, esResponse, respOpts) { - let write = new TabbedAggResponseWriter(vis, respOpts); + const write = new TabbedAggResponseWriter(vis, respOpts); - let topLevelBucket = _.assign({}, esResponse.aggregations, { + const topLevelBucket = _.assign({}, esResponse.aggregations, { doc_count: esResponse.hits.total }); @@ -31,13 +31,13 @@ export default function tabifyAggResponseProvider(Private, Notifier) { * @returns {undefined} */ function collectBucket(write, bucket, key) { - let agg = write.aggStack.shift(); + const agg = write.aggStack.shift(); switch (agg.schema.group) { case 'buckets': - let buckets = new Buckets(bucket[agg.id]); + const buckets = new Buckets(bucket[agg.id]); if (buckets.length) { - let splitting = write.canSplit && agg.schema.name === 'split'; + const splitting = write.canSplit && agg.schema.name === 'split'; if (splitting) { write.split(agg, buckets, function forEachBucket(subBucket, key) { collectBucket(write, subBucket, agg.getKey(subBucket), key); @@ -63,7 +63,7 @@ export default function tabifyAggResponseProvider(Private, Notifier) { } break; case 'metrics': - let value = agg.getValue(bucket); + const value = agg.getValue(bucket); write.cell(agg, value, function () { if (!write.aggStack.length) { // row complete @@ -82,7 +82,7 @@ export default function tabifyAggResponseProvider(Private, Notifier) { // write empty values for each bucket agg, then write // the metrics from the initial bucket using collectBucket() function passEmptyBuckets(write, bucket, key) { - let agg = write.aggStack.shift(); + const agg = write.aggStack.shift(); switch (agg.schema.group) { case 'metrics': diff --git a/src/ui/public/agg_table/__tests__/_group.js b/src/ui/public/agg_table/__tests__/_group.js index 88c7cb92092ed..31bdc70eb5aa5 100644 --- a/src/ui/public/agg_table/__tests__/_group.js +++ b/src/ui/public/agg_table/__tests__/_group.js @@ -34,13 +34,13 @@ describe('AggTableGroup Directive', function () { it('renders a simple split response properly', function () { - let vis = new Vis(indexPattern, 'table'); + const vis = new Vis(indexPattern, 'table'); $scope.group = tabifyAggResponse(vis, fixtures.metricOnly); $scope.sort = { columnIndex: null, direction: null }; - let $el = $(''); + const $el = $(''); $compile($el)($scope); $scope.$digest(); @@ -50,7 +50,7 @@ describe('AggTableGroup Directive', function () { }); it('renders nothing if the table list is empty', function () { - let $el = $(''); + const $el = $(''); $scope.group = { tables: [] @@ -59,12 +59,12 @@ describe('AggTableGroup Directive', function () { $compile($el)($scope); $scope.$digest(); - let $subTables = $el.find('kbn-agg-table'); + const $subTables = $el.find('kbn-agg-table'); expect($subTables.size()).to.be(0); }); it('renders a complex response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -77,15 +77,15 @@ describe('AggTableGroup Directive', function () { agg.id = 'agg_' + (i + 1); }); - let group = $scope.group = tabifyAggResponse(vis, fixtures.threeTermBuckets); - let $el = $(''); + const group = $scope.group = tabifyAggResponse(vis, fixtures.threeTermBuckets); + const $el = $(''); $compile($el)($scope); $scope.$digest(); - let $subTables = $el.find('kbn-agg-table'); + const $subTables = $el.find('kbn-agg-table'); expect($subTables.size()).to.be(3); - let $subTableHeaders = $el.find('.agg-table-group-header'); + const $subTableHeaders = $el.find('.agg-table-group-header'); expect($subTableHeaders.size()).to.be(3); $subTableHeaders.each(function (i) { diff --git a/src/ui/public/agg_table/__tests__/_table.js b/src/ui/public/agg_table/__tests__/_table.js index 062bd6ccfb37f..b6b1f5cf75821 100644 --- a/src/ui/public/agg_table/__tests__/_table.js +++ b/src/ui/public/agg_table/__tests__/_table.js @@ -35,10 +35,10 @@ describe('AggTable Directive', function () { it('renders a simple response properly', function () { - let vis = new Vis(indexPattern, 'table'); + const vis = new Vis(indexPattern, 'table'); $scope.table = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(1); @@ -48,14 +48,14 @@ describe('AggTable Directive', function () { it('renders nothing if the table is empty', function () { $scope.table = null; - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(0); }); it('renders a complex response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -69,27 +69,27 @@ describe('AggTable Directive', function () { }); $scope.table = tabifyAggResponse(vis, fixtures.threeTermBuckets, { canSplit: false }); - let $el = $(''); + const $el = $(''); $compile($el)($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(1); - let $rows = $el.find('tbody tr'); + const $rows = $el.find('tbody tr'); expect($rows.size()).to.be.greaterThan(0); function validBytes(str) { expect(str).to.match(/^\d+$/); - let bytesAsNum = _.parseInt(str); + const bytesAsNum = _.parseInt(str); expect(bytesAsNum === 0 || bytesAsNum > 1000).to.be.ok(); } $rows.each(function (i) { // 6 cells in every row - let $cells = $(this).find('td'); + const $cells = $(this).find('td'); expect($cells.size()).to.be(6); - let txts = $cells.map(function () { + const txts = $cells.map(function () { return $(this).text().trim(); }); @@ -109,11 +109,11 @@ describe('AggTable Directive', function () { describe('aggTable.toCsv()', function () { it('escapes and formats the rows and columns properly', function () { - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; $tableScope.table = { columns: [ @@ -150,13 +150,13 @@ describe('AggTable Directive', function () { }); it('calls _saveAs properly', function () { - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; - let saveAs = sinon.stub(aggTable, '_saveAs'); + const saveAs = sinon.stub(aggTable, '_saveAs'); $tableScope.table = { columns: [ { title: 'one' }, @@ -172,7 +172,7 @@ describe('AggTable Directive', function () { aggTable.exportAsCsv(); expect(saveAs.callCount).to.be(1); - let call = saveAs.getCall(0); + const call = saveAs.getCall(0); expect(call.args[0]).to.be.a(FakeBlob); expect(call.args[0].slices).to.eql([ 'one,two,"with double-quotes("")"' + '\r\n' + @@ -185,12 +185,12 @@ describe('AggTable Directive', function () { }); it('should use the export-title attribute', function () { - let expected = 'export file name'; - let $el = $compile(``)($scope); + const expected = 'export file name'; + const $el = $compile(``)($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; $tableScope.table = { columns: [], rows: [] diff --git a/src/ui/public/agg_table/agg_table.js b/src/ui/public/agg_table/agg_table.js index a6853254ef8ec..5b05afa7f929b 100644 --- a/src/ui/public/agg_table/agg_table.js +++ b/src/ui/public/agg_table/agg_table.js @@ -27,7 +27,7 @@ uiModules return compileRecursiveDirective.compile($el); }, controller: function ($scope) { - let self = this; + const self = this; self._saveAs = require('@spalger/filesaver').saveAs; self.csv = { @@ -36,15 +36,15 @@ uiModules }; self.exportAsCsv = function (formatted) { - let csv = new Blob([self.toCsv(formatted)], { type: 'text/plain' }); + const csv = new Blob([self.toCsv(formatted)], { type: 'text/plain' }); self._saveAs(csv, self.csv.filename); }; self.toCsv = function (formatted) { - let rows = $scope.table.rows; - let columns = formatted ? $scope.formattedColumns : $scope.table.columns; - let nonAlphaNumRE = /[^a-zA-Z0-9]/; - let allDoubleQuoteRE = /"/g; + const rows = $scope.table.rows; + const columns = formatted ? $scope.formattedColumns : $scope.table.columns; + const nonAlphaNumRE = /[^a-zA-Z0-9]/; + const allDoubleQuoteRE = /"/g; function escape(val) { if (!formatted && _.isObject(val)) val = val.valueOf(); @@ -56,7 +56,7 @@ uiModules } // escape each cell in each row - let csvRows = rows.map(function (row) { + const csvRows = rows.map(function (row) { return row.map(escape); }); @@ -71,7 +71,7 @@ uiModules }; $scope.$watch('table', function () { - let table = $scope.table; + const table = $scope.table; if (!table) { $scope.rows = null; @@ -82,14 +82,14 @@ uiModules self.csv.filename = ($scope.exportTitle || table.title() || 'table') + '.csv'; $scope.rows = table.rows; $scope.formattedColumns = table.columns.map(function (col, i) { - let agg = $scope.table.aggConfig(col); - let field = agg.field(); - let formattedColumn = { + const agg = $scope.table.aggConfig(col); + const field = agg.field(); + const formattedColumn = { title: col.title, filterable: field && field.filterable && agg.schema.group === 'buckets' }; - let last = i === (table.columns.length - 1); + const last = i === (table.columns.length - 1); if (last || (agg.schema.group === 'metrics')) { formattedColumn.class = 'visualize-table-right'; diff --git a/src/ui/public/agg_table/agg_table_group.js b/src/ui/public/agg_table/agg_table_group.js index 2cd1031182ba4..cff0e1180f951 100644 --- a/src/ui/public/agg_table/agg_table_group.js +++ b/src/ui/public/agg_table/agg_table_group.js @@ -28,10 +28,10 @@ uiModules if (!group || !group.tables.length) return; - let firstTable = group.tables[0]; - let params = firstTable.aggConfig && firstTable.aggConfig.params; + const firstTable = group.tables[0]; + const params = firstTable.aggConfig && firstTable.aggConfig.params; // render groups that have Table children as if they were rows, because iteration is cleaner - let childLayout = (params && !params.row) ? 'columns' : 'rows'; + const childLayout = (params && !params.row) ? 'columns' : 'rows'; $scope[childLayout] = group.tables; }); diff --git a/src/ui/public/agg_types/__tests__/agg_param_writer.js b/src/ui/public/agg_types/__tests__/agg_param_writer.js index 58d113f2e6c5c..0de3f8b1eb5b5 100644 --- a/src/ui/public/agg_types/__tests__/agg_param_writer.js +++ b/src/ui/public/agg_types/__tests__/agg_param_writer.js @@ -4,10 +4,10 @@ import AggTypesIndexProvider from 'ui/agg_types/index'; import RegistryVisTypesProvider from 'ui/registry/vis_types'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; module.exports = function AggParamWriterHelper(Private) { - let Vis = Private(VisProvider); - let aggTypes = Private(AggTypesIndexProvider); - let visTypes = Private(RegistryVisTypesProvider); - let stubbedLogstashIndexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const Vis = Private(VisProvider); + const aggTypes = Private(AggTypesIndexProvider); + const visTypes = Private(RegistryVisTypesProvider); + const stubbedLogstashIndexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); /** * Helper object for writing aggParams. Specify an aggType and it will find a vis & schema, and @@ -29,7 +29,7 @@ module.exports = function AggParamWriterHelper(Private) { * @param {string} opts.aggType - the name of the aggType we want to test. ('histogram', 'filter', etc.) */ function AggParamWriter(opts) { - let self = this; + const self = this; self.aggType = opts.aggType; if (_.isString(self.aggType)) { @@ -47,7 +47,7 @@ module.exports = function AggParamWriterHelper(Private) { // find a suitable vis type and schema _.find(visTypes, function (visType) { - let schema = _.find(visType.schemas.all, function (schema) { + const schema = _.find(visType.schemas.all, function (schema) { // type, type, type, type, type... :( return schema.group === self.aggType.type; }); @@ -69,7 +69,7 @@ module.exports = function AggParamWriterHelper(Private) { } AggParamWriter.prototype.write = function (paramValues) { - let self = this; + const self = this; paramValues = _.clone(paramValues); if (self.aggType.params.byName.field && !paramValues.field) { @@ -90,7 +90,7 @@ module.exports = function AggParamWriterHelper(Private) { }] }); - let aggConfig = _.find(self.vis.aggs, function (aggConfig) { + const aggConfig = _.find(self.vis.aggs, function (aggConfig) { return aggConfig.type === self.aggType; }); diff --git a/src/ui/public/agg_types/__tests__/agg_params.js b/src/ui/public/agg_types/__tests__/agg_params.js index 1eff825ecb769..84d06c6b6471e 100644 --- a/src/ui/public/agg_types/__tests__/agg_params.js +++ b/src/ui/public/agg_types/__tests__/agg_params.js @@ -28,11 +28,11 @@ describe('AggParams class', function () { describe('constructor args', function () { it('accepts an array of param defs', function () { - let params = [ + const params = [ { name: 'one' }, { name: 'two' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams).to.be.an(Array); @@ -42,43 +42,43 @@ describe('AggParams class', function () { describe('AggParam creation', function () { it('Uses the FieldAggParam class for params with the name "field"', function () { - let params = [ + const params = [ { name: 'field' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(FieldAggParam); }); it('Uses the OptionedAggParam class for params of type "optioned"', function () { - let params = [ + const params = [ { name: 'interval', type: 'optioned' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(OptionedAggParam); }); it('Uses the RegexAggParam class for params of type "regex"', function () { - let params = [ + const params = [ { name: 'exclude', type: 'regex' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(RegexAggParam); }); it('Always converts the params to a BaseAggParam', function () { - let params = [ + const params = [ { name: 'height', editor: 'high' @@ -92,7 +92,7 @@ describe('AggParams class', function () { editor: 'small' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(BaseAggParam).to.have.property('callCount', params.length); expect(FieldAggParam).to.have.property('callCount', 0); diff --git a/src/ui/public/agg_types/__tests__/agg_type.js b/src/ui/public/agg_types/__tests__/agg_type.js index 94dbcab47d495..f8bb6616fe9aa 100644 --- a/src/ui/public/agg_types/__tests__/agg_type.js +++ b/src/ui/public/agg_types/__tests__/agg_type.js @@ -39,7 +39,7 @@ describe('AggType Class', function () { }); describe('application of config properties', function () { - let copiedConfigProps = [ + const copiedConfigProps = [ 'name', 'title', 'makeLabel', @@ -48,11 +48,11 @@ describe('AggType Class', function () { describe('"' + copiedConfigProps.join('", "') + '"', function () { it('assigns the config value to itself', function () { - let config = _.transform(copiedConfigProps, function (config, prop) { + const config = _.transform(copiedConfigProps, function (config, prop) { config[prop] = {}; }, {}); - let aggType = new AggType(config); + const aggType = new AggType(config); copiedConfigProps.forEach(function (prop) { expect(aggType[prop]).to.be(config[prop]); @@ -62,7 +62,7 @@ describe('AggType Class', function () { describe('makeLabel', function () { it('makes a function when the makeLabel config is not specified', function () { - let someGetter = function () {}; + const someGetter = function () {}; let aggType = new AggType({ makeLabel: someGetter @@ -81,7 +81,7 @@ describe('AggType Class', function () { describe('getFormat', function () { it('returns the formatter for the aggConfig', function () { - let aggType = new AggType({}); + const aggType = new AggType({}); let vis = new Vis(indexPattern, { type: 'histogram', @@ -112,9 +112,9 @@ describe('AggType Class', function () { }); it('can be overridden via config', function () { - let someGetter = function () {}; + const someGetter = function () {}; - let aggType = new AggType({ + const aggType = new AggType({ getFormat: someGetter }); @@ -128,7 +128,7 @@ describe('AggType Class', function () { }); it('defaults to AggParams object with JSON param', function () { - let aggType = new AggType({ + const aggType = new AggType({ name: 'smart agg' }); @@ -139,7 +139,7 @@ describe('AggType Class', function () { }); it('can disable customLabel', function () { - let aggType = new AggType({ + const aggType = new AggType({ name: 'smart agg', customLabels: false }); @@ -149,13 +149,13 @@ describe('AggType Class', function () { }); it('passes the params arg directly to the AggParams constructor', function () { - let params = [ + const params = [ {name: 'one'}, {name: 'two'} ]; - let paramLength = params.length + 2; // json and custom label are always appended + const paramLength = params.length + 2; // json and custom label are always appended - let aggType = new AggType({ + const aggType = new AggType({ name: 'bucketeer', params: params }); @@ -169,8 +169,8 @@ describe('AggType Class', function () { describe('getResponseAggs', function () { it('copies the value', function () { - let football = {}; - let aggType = new AggType({ + const football = {}; + const aggType = new AggType({ getResponseAggs: football }); @@ -178,7 +178,7 @@ describe('AggType Class', function () { }); it('defaults to _.noop', function () { - let aggType = new AggType({}); + const aggType = new AggType({}); expect(aggType.getResponseAggs).to.be(_.noop); }); diff --git a/src/ui/public/agg_types/__tests__/bucket_count_between.js b/src/ui/public/agg_types/__tests__/bucket_count_between.js index 75c2a4e46fdf7..61f0828f4b14f 100644 --- a/src/ui/public/agg_types/__tests__/bucket_count_between.js +++ b/src/ui/public/agg_types/__tests__/bucket_count_between.js @@ -32,7 +32,7 @@ describe('bucketCountBetween util', function () { })); it('returns a positive number when a is before b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -46,14 +46,14 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = vis.aggs.byTypeName.terms[0]; - let count = bucketCountBetween(a, b); + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.terms[0]; + const count = bucketCountBetween(a, b); expect(isNegative(count)).to.be(false); }); it('returns a negative number when a is after b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -67,14 +67,14 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.terms[0]; - let b = vis.aggs.byTypeName.date_histogram[0]; - let count = bucketCountBetween(a, b); + const a = vis.aggs.byTypeName.terms[0]; + const b = vis.aggs.byTypeName.date_histogram[0]; + const count = bucketCountBetween(a, b); expect(isNegative(count)).to.be(true); }); it('returns 0 when there are no buckets between a and b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -88,13 +88,13 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = vis.aggs.byTypeName.terms[0]; + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.terms[0]; expect(bucketCountBetween(a, b)).to.be(0); }); it('returns null when b is not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -104,8 +104,8 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = new AggConfig(vis, { + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = new AggConfig(vis, { type: 'terms', schema: 'segment' }); @@ -114,7 +114,7 @@ describe('bucketCountBetween util', function () { }); it('returns null when a is not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -124,27 +124,27 @@ describe('bucketCountBetween util', function () { ] }); - let a = new AggConfig(vis, { + const a = new AggConfig(vis, { type: 'terms', schema: 'segment' }); - let b = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.date_histogram[0]; expect(bucketCountBetween(a, b)).to.be(null); }); it('returns null when a and b are not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let a = new AggConfig(vis, { + const a = new AggConfig(vis, { type: 'terms', schema: 'segment' }); - let b = new AggConfig(vis, { + const b = new AggConfig(vis, { type: 'date_histogram', schema: 'segment' }); @@ -154,14 +154,14 @@ describe('bucketCountBetween util', function () { function countTest(pre, post) { return function () { - let schemas = visTypes.byName.histogram.schemas.buckets; + const schemas = visTypes.byName.histogram.schemas.buckets; // slow for this test is actually somewhere around 1/2 a sec this.slow(500); function randBucketAggForVis(vis) { - let schema = _.sample(schemas); - let aggType = _.sample(aggTypes.byType.buckets); + const schema = _.sample(schemas); + const aggType = _.sample(aggTypes.byType.buckets); return new AggConfig(vis, { schema: schema, @@ -170,18 +170,18 @@ describe('bucketCountBetween util', function () { } _.times(50, function (n) { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let randBucketAgg = _.partial(randBucketAggForVis, vis); + const randBucketAgg = _.partial(randBucketAggForVis, vis); - let a = randBucketAgg(); - let b = randBucketAgg(); + const a = randBucketAgg(); + const b = randBucketAgg(); // create n aggs between a and b - let aggs = []; + const aggs = []; aggs.fill = function (n) { for (let i = 0; i < n; i++) { aggs.push(randBucketAgg()); diff --git a/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js b/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js index c4b2650cd6219..e0511b95f948c 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js +++ b/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js @@ -6,7 +6,7 @@ describe('Geohash Agg', function () { describe('write', function () { - let paramWriter = new AggTypesBucketsGeoHashProvider(function PrivateMock() { + const paramWriter = new AggTypesBucketsGeoHashProvider(function PrivateMock() { return function BucketMock(geohashProvider) { return geohashProvider.params[4]; }; diff --git a/src/ui/public/agg_types/__tests__/buckets/_histogram.js b/src/ui/public/agg_types/__tests__/buckets/_histogram.js index 325e91ecf56c9..ea66ce28e7a94 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/_histogram.js @@ -28,7 +28,7 @@ describe('Histogram Agg', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { - let AggParamWriter = Private(AggParamWriterProvider); + const AggParamWriter = Private(AggParamWriterProvider); paramWriter = new AggParamWriter({ aggType: 'histogram' }); })); @@ -36,18 +36,18 @@ describe('Histogram Agg', function () { // reads aggConfig.params.interval, writes to dsl.interval it('accepts a number', function () { - let output = paramWriter.write({ interval: 100 }); + const output = paramWriter.write({ interval: 100 }); expect(output.params).to.have.property('interval', 100); }); it('accepts a string', function () { - let output = paramWriter.write({ interval: '10' }); + const output = paramWriter.write({ interval: '10' }); expect(output.params).to.have.property('interval', 10); }); it('fails on non-numeric values', function () { // template validation prevents this from users, not devs - let output = paramWriter.write({ interval: [] }); + const output = paramWriter.write({ interval: [] }); expect(isNaN(output.params.interval)).to.be.ok(); }); }); @@ -81,7 +81,7 @@ describe('Histogram Agg', function () { describe('extended_bounds', function () { it('writes when only eb.min is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { min: 0 } }); @@ -90,7 +90,7 @@ describe('Histogram Agg', function () { }); it('writes when only eb.max is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { max: 0 } }); @@ -99,7 +99,7 @@ describe('Histogram Agg', function () { }); it('writes when both eb.min and eb.max are set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { min: 99, max: 100 } }); @@ -108,7 +108,7 @@ describe('Histogram Agg', function () { }); it('does not write when nothing is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: {} }); @@ -116,7 +116,7 @@ describe('Histogram Agg', function () { }); it('does not write when min_doc_count is false', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: false, extended_bounds: { min: 99, max: 100 } }); diff --git a/src/ui/public/agg_types/__tests__/buckets/_range.js b/src/ui/public/agg_types/__tests__/buckets/_range.js index a25c447bdd38f..a9a5744250651 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/_range.js @@ -9,7 +9,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; describe('Range Agg', function () { - let buckets = values(resp.aggregations[1].buckets); + const buckets = values(resp.aggregations[1].buckets); let range; let Vis; @@ -21,7 +21,7 @@ describe('Range Agg', function () { Vis = Private(VisProvider); indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let BytesFormat = Private(RegistryFieldFormatsProvider).byId.bytes; + const BytesFormat = Private(RegistryFieldFormatsProvider).byId.bytes; indexPattern.fieldFormatMap.bytes = new BytesFormat({ pattern: '0,0.[000] b' @@ -32,7 +32,7 @@ describe('Range Agg', function () { describe('formating', function () { it('formats bucket keys properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -49,8 +49,8 @@ describe('Range Agg', function () { ] }); - let agg = vis.aggs.byTypeName.range[0]; - let format = function (val) { + const agg = vis.aggs.byTypeName.range[0]; + const format = function (val) { return agg.fieldFormatter()(agg.getKey(val)); }; expect(format(buckets[0])).to.be('-∞ to 1 KB'); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js index 9efc4515038aa..1f092220bbedf 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js @@ -25,10 +25,10 @@ describe('AggConfig Filters', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let Vis = Private(VisProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let createFilter = Private(AggTypesBucketsCreateFilterDateHistogramProvider); - let TimeBuckets = Private(TimeBucketsProvider); + const Vis = Private(VisProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const createFilter = Private(AggTypesBucketsCreateFilterDateHistogramProvider); + const TimeBuckets = Private(TimeBucketsProvider); intervalOptions = Private(AggTypesBucketsIntervalOptionsProvider); init = function (interval, duration) { @@ -51,7 +51,7 @@ describe('AggConfig Filters', function () { bucketKey = _.sample(aggResp.aggregations['1'].buckets).key; bucketStart = moment(bucketKey); - let timePad = moment.duration(duration / 2); + const timePad = moment.duration(duration / 2); agg.buckets.setBounds({ min: bucketStart.clone().subtract(timePad), max: bucketStart.clone().add(timePad), @@ -68,7 +68,7 @@ describe('AggConfig Filters', function () { expect(filter).to.have.property('range'); expect(filter.range).to.have.property(field.name); - let fieldParams = filter.range[field.name]; + const fieldParams = filter.range[field.name]; expect(fieldParams).to.have.property('gte'); expect(fieldParams.gte).to.be.a('number'); @@ -98,8 +98,8 @@ describe('AggConfig Filters', function () { init(option.val, duration); - let interval = agg.buckets.getInterval(); - let params = filter.range[field.name]; + const interval = agg.buckets.getInterval(); + const params = filter.range[field.name]; expect(params.gte).to.be(+bucketStart); expect(params.lt).to.be(+bucketStart.clone().add(interval)); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js index 117852228b6cc..5beaf4ba72409 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for date_range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -38,8 +38,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.date_range[0]; - let filter = createFilter(aggConfig, 'February 1st, 2015 to February 7th, 2015'); + const aggConfig = vis.aggs.byTypeName.date_range[0]; + const filter = createFilter(aggConfig, 'February 1st, 2015 to February 7th, 2015'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js index 43069575965af..53c5e524f66b8 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return a filters filter', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -39,8 +39,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.filters[0]; - let filter = createFilter(aggConfig, '_type:nginx'); + const aggConfig = vis.aggs.byTypeName.filters[0]; + const filter = createFilter(aggConfig, '_type:nginx'); expect(_.omit(filter, 'meta')).to.eql(aggConfig.params.filters[1].input); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js index 702cd0ea746b7..69af6d4a7cd48 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return an range filter for histogram', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -34,8 +34,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.histogram[0]; - let filter = createFilter(aggConfig, 2048); + const aggConfig = vis.aggs.byTypeName.histogram[0]; + const filter = createFilter(aggConfig, 2048); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); expect(filter).to.have.property('range'); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js index d98e8f0727efc..8f028e9c20591 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js @@ -21,7 +21,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for ip_range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -40,8 +40,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.ip_range[0]; - let filter = createFilter(aggConfig, '0.0.0.0-1.1.1.1'); + const aggConfig = vis.aggs.byTypeName.ip_range[0]; + const filter = createFilter(aggConfig, '0.0.0.0-1.1.1.1'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); @@ -51,7 +51,7 @@ describe('AggConfig Filters', function () { }); it('should return a range filter for ip_range agg using a CIDR mask', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -70,8 +70,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.ip_range[0]; - let filter = createFilter(aggConfig, '67.129.65.201/27'); + const aggConfig = vis.aggs.byTypeName.ip_range[0]; + const filter = createFilter(aggConfig, '67.129.65.201/27'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js index b6ccd71d38cd5..023141bba6382 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js @@ -21,7 +21,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -37,8 +37,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.range[0]; - let filter = createFilter(aggConfig, { gte: 1024, lt: 2048.0 }); + const aggConfig = vis.aggs.byTypeName.range[0]; + const filter = createFilter(aggConfig, { gte: 1024, lt: 2048.0 }); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js index c0a67aa283655..50056b516d42e 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js @@ -21,12 +21,12 @@ describe('AggConfig Filters', function () { })); it('should return a match filter for terms', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' } } ] }); - let aggConfig = vis.aggs.byTypeName.terms[0]; - let filter = createFilter(aggConfig, 'apache'); + const aggConfig = vis.aggs.byTypeName.terms[0]; + const filter = createFilter(aggConfig, 'apache'); expect(filter).to.have.property('query'); expect(filter.query).to.have.property('match'); expect(filter.query.match).to.have.property('_type'); diff --git a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js index 6d2e4834418eb..62bc7944e747b 100644 --- a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js +++ b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js @@ -17,7 +17,7 @@ describe('editor', function () { beforeEach(ngMock.inject(function (Private, $injector, $compile) { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let Vis = Private(VisProvider); + const Vis = Private(VisProvider); /** * Render the AggParams editor for the date histogram aggregation @@ -38,8 +38,8 @@ describe('editor', function () { ] }); - let $el = $(''); - let $parentScope = $injector.get('$rootScope').$new(); + const $el = $(''); + const $parentScope = $injector.get('$rootScope').$new(); agg = $parentScope.agg = vis.aggs.bySchemaName.segment[0]; $parentScope.groupName = 'buckets'; @@ -48,10 +48,10 @@ describe('editor', function () { $scope = $el.scope(); $scope.$digest(); - let $inputs = $('vis-agg-param-editor', $el); + const $inputs = $('vis-agg-param-editor', $el); return _.transform($inputs.toArray(), function (inputs, e) { - let $el = $(e); - let $scope = $el.scope(); + const $el = $(e); + const $scope = $el.scope(); inputs[$scope.aggParam.name] = { $el: $el, @@ -107,7 +107,7 @@ describe('editor', function () { expect(params.interval.modelValue().val).to.be('auto'); expect(params.field.modelValue().name).to.be(indexPattern.timeFieldName); - let field = _.find(indexPattern.fields, function (f) { + const field = _.find(indexPattern.fields, function (f) { return f.type === 'date' && f.name !== indexPattern.timeFieldName; }); diff --git a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js index 4e6c6870f2574..5a0c06d6811b3 100644 --- a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js +++ b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js @@ -18,9 +18,9 @@ describe('params', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let AggParamWriter = Private(AggParamWriterProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let timefilter = $injector.get('timefilter'); + const AggParamWriter = Private(AggParamWriterProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const timefilter = $injector.get('timefilter'); timeField = indexPattern.timeFieldName; aggTypes = Private(AggTypesIndexProvider); @@ -31,7 +31,7 @@ describe('params', function () { return paramWriter.write({ interval: interval, field: timeField }); }; - let now = moment(); + const now = moment(); setTimeBounds = function (n, units) { timefilter.enabled = true; timefilter.getBounds = _.constant({ @@ -43,24 +43,24 @@ describe('params', function () { describe('interval', function () { it('accepts a valid interval', function () { - let output = writeInterval('d'); + const output = writeInterval('d'); expect(output.params).to.have.property('interval', '1d'); }); it('ignores invalid intervals', function () { - let output = writeInterval('foo'); + const output = writeInterval('foo'); expect(output.params).to.have.property('interval', '0ms'); }); it('automatically picks an interval', function () { setTimeBounds(15, 'm'); - let output = writeInterval('auto'); + const output = writeInterval('auto'); expect(output.params.interval).to.be('30s'); }); it('scales up the interval if it will make too many buckets', function () { setTimeBounds(30, 'm'); - let output = writeInterval('s'); + const output = writeInterval('s'); expect(output.params.interval).to.be('10s'); expect(output.metricScaleText).to.be('second'); expect(output.metricScale).to.be(0.1); @@ -68,30 +68,30 @@ describe('params', function () { it('does not scale down the interval', function () { setTimeBounds(1, 'm'); - let output = writeInterval('h'); + const output = writeInterval('h'); expect(output.params.interval).to.be('1h'); expect(output.metricScaleText).to.be(undefined); expect(output.metricScale).to.be(undefined); }); describe('only scales when all metrics are sum or count', function () { - let tests = [ + const tests = [ [ false, 'avg', 'count', 'sum' ], [ true, 'count', 'sum' ], [ false, 'count', 'cardinality' ] ]; tests.forEach(function (test) { - let should = test.shift(); - let typeNames = test.slice(); + const should = test.shift(); + const typeNames = test.slice(); it(typeNames.join(', ') + ' should ' + (should ? '' : 'not') + ' scale', function () { setTimeBounds(1, 'y'); - let vis = paramWriter.vis; + const vis = paramWriter.vis; vis.aggs.splice(0); - let histoConfig = new AggConfig(vis, { + const histoConfig = new AggConfig(vis, { type: aggTypes.byName.date_histogram, schema: 'segment', params: { interval: 's', field: timeField } @@ -106,7 +106,7 @@ describe('params', function () { })); }); - let output = histoConfig.write(); + const output = histoConfig.write(); expect(_.has(output, 'metricScale')).to.be(should); }); }); @@ -115,9 +115,9 @@ describe('params', function () { describe('extended_bounds', function () { it('should write a long value if a moment passed in', function () { - let then = moment(0); - let now = moment(500); - let output = paramWriter.write({ + const then = moment(0); + const now = moment(500); + const output = paramWriter.write({ extended_bounds: { min: then, max: now @@ -133,9 +133,9 @@ describe('params', function () { }); it('should write a long if a long is passed', function () { - let then = 0; - let now = 500; - let output = paramWriter.write({ + const then = 0; + const now = 500; + const output = paramWriter.write({ extended_bounds: { min: then, max: now diff --git a/src/ui/public/agg_types/__tests__/controls/number_list.js b/src/ui/public/agg_types/__tests__/controls/number_list.js index 3c7204b0682b8..121501dcbfd7b 100644 --- a/src/ui/public/agg_types/__tests__/controls/number_list.js +++ b/src/ui/public/agg_types/__tests__/controls/number_list.js @@ -13,15 +13,15 @@ describe('NumberList directive', function () { function onlyValidValues() { return $el.find('[ng-model]').toArray().map(function (el) { - let ngModel = $(el).controller('ngModel'); + const ngModel = $(el).controller('ngModel'); return ngModel.$valid ? ngModel.$modelValue : undefined; }); } beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($injector) { - let $compile = $injector.get('$compile'); - let $rootScope = $injector.get('$rootScope'); + const $compile = $injector.get('$compile'); + const $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $el = $(''); @@ -75,7 +75,7 @@ describe('NumberList directive', function () { it('shift-up increases by 0.1', function () { compile([4.8]); - let seq = [ + const seq = [ { type: 'press', key: 'shift', @@ -111,7 +111,7 @@ describe('NumberList directive', function () { it('shift-down decreases by 0.1', function () { compile([5.1]); - let seq = [ + const seq = [ { type: 'press', key: 'shift', @@ -135,12 +135,12 @@ describe('NumberList directive', function () { it('maintains valid number', function () { compile([9, 11, 13]); - let seq = [ + const seq = [ 'down', // 10 (11 - 1) 'down' // 10 (limited by 9) ]; - let getEl = function () { return $el.find('input').eq(1); }; + const getEl = function () { return $el.find('input').eq(1); }; return simulateKeys(getEl, seq) .then(function () { diff --git a/src/ui/public/agg_types/__tests__/metrics/median.js b/src/ui/public/agg_types/__tests__/metrics/median.js index 3524031c62029..81589c4bf6f48 100644 --- a/src/ui/public/agg_types/__tests__/metrics/median.js +++ b/src/ui/public/agg_types/__tests__/metrics/median.js @@ -17,7 +17,7 @@ describe('AggTypeMetricMedianProvider class', function () { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); aggTypeMetricMedian = Private(AggTypeMetricMedianProvider); - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { 'title': 'New Visualization', 'type': 'metric', 'params': { @@ -42,7 +42,7 @@ describe('AggTypeMetricMedianProvider class', function () { // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggDsl = aggConfig.toDsl(); })); diff --git a/src/ui/public/agg_types/__tests__/metrics/std_deviation.js b/src/ui/public/agg_types/__tests__/metrics/std_deviation.js index 90666b65e5dbd..1433ed793ccaa 100644 --- a/src/ui/public/agg_types/__tests__/metrics/std_deviation.js +++ b/src/ui/public/agg_types/__tests__/metrics/std_deviation.js @@ -18,37 +18,37 @@ describe('AggTypeMetricStandardDeviationProvider class', function () { })); it('uses the custom label if it is set', function () { - let vis = new Vis(indexPattern, {}); + const vis = new Vis(indexPattern, {}); // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggConfig.params.customLabel = 'custom label'; aggConfig.params.field = { displayName: 'memory' }; - let responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); - let lowerStdDevLabel = responseAggs[0].makeLabel(); - let upperStdDevLabel = responseAggs[1].makeLabel(); + const responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); + const lowerStdDevLabel = responseAggs[0].makeLabel(); + const upperStdDevLabel = responseAggs[1].makeLabel(); expect(lowerStdDevLabel).to.be('Lower custom label'); expect(upperStdDevLabel).to.be('Upper custom label'); }); it('uses the default labels if custom label is not set', function () { - let vis = new Vis(indexPattern, {}); + const vis = new Vis(indexPattern, {}); // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggConfig.params.field = { displayName: 'memory' }; - let responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); - let lowerStdDevLabel = responseAggs[0].makeLabel(); - let upperStdDevLabel = responseAggs[1].makeLabel(); + const responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); + const lowerStdDevLabel = responseAggs[0].makeLabel(); + const upperStdDevLabel = responseAggs[1].makeLabel(); expect(lowerStdDevLabel).to.be('Lower Standard Deviation of memory'); expect(upperStdDevLabel).to.be('Upper Standard Deviation of memory'); diff --git a/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js b/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js index 47455e418a38a..df28b1a06b2d4 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js +++ b/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js @@ -21,15 +21,15 @@ describe('calculateInterval()', function () { calculateInterval = Private(AggTypesParamTypesCalculateIntervalProvider); })); - let testInterval = function (option, expected) { - let msg = 'should return ' + JSON.stringify(expected) + ' for ' + option; + const testInterval = function (option, expected) { + const msg = 'should return ' + JSON.stringify(expected) + ' for ' + option; it(msg, function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp', interval: option } } ] }); - let aggConfig = vis.aggs.byTypeName.date_histogram[0]; - let interval = calculateInterval(aggConfig); + const aggConfig = vis.aggs.byTypeName.date_histogram[0]; + const interval = calculateInterval(aggConfig); _.each(expected, function (val, key) { expect(interval).to.have.property(key, val); }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_field.js b/src/ui/public/agg_types/__tests__/param_types/_field.js index cc2679fc0d4b8..cf9927ef19ffa 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_field.js +++ b/src/ui/public/agg_types/__tests__/param_types/_field.js @@ -17,7 +17,7 @@ describe('Field', function () { describe('constructor', function () { it('it is an instance of BaseAggParam', function () { - let aggParam = new FieldAggParam({ + const aggParam = new FieldAggParam({ name: 'field' }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_optioned.js b/src/ui/public/agg_types/__tests__/param_types/_optioned.js index 69165309fb12d..ad6db067548de 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_optioned.js +++ b/src/ui/public/agg_types/__tests__/param_types/_optioned.js @@ -17,7 +17,7 @@ describe('Optioned', function () { describe('constructor', function () { it('it is an instance of BaseAggParam', function () { - let aggParam = new OptionedAggParam({ + const aggParam = new OptionedAggParam({ name: 'some_param', type: 'optioned' }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_raw_json.js b/src/ui/public/agg_types/__tests__/param_types/_raw_json.js index 86c69ee620dad..53bfd8b8a5a8f 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_raw_json.js +++ b/src/ui/public/agg_types/__tests__/param_types/_raw_json.js @@ -6,7 +6,7 @@ import AggTypesParamTypesRawJsonProvider from 'ui/agg_types/param_types/raw_json module.exports = describe('JSON', function () { - let paramName = 'json_test'; + const paramName = 'json_test'; let BaseAggParam; let JsonAggParam; let aggParam; @@ -15,7 +15,7 @@ module.exports = describe('JSON', function () { function initAggParam(config) { config = config || {}; - let defaults = { + const defaults = { name: paramName, type: 'json' }; @@ -59,7 +59,7 @@ module.exports = describe('JSON', function () { }); it('should append param when valid JSON', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output' }); @@ -75,7 +75,7 @@ module.exports = describe('JSON', function () { }); it('should not overwrite existing params', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output', existing: 'should be used' }); @@ -88,7 +88,7 @@ module.exports = describe('JSON', function () { }); it('should drop nulled params', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output', field: null }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_regex.js b/src/ui/public/agg_types/__tests__/param_types/_regex.js index a29c7b7d812e3..d426da4d40db2 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_regex.js +++ b/src/ui/public/agg_types/__tests__/param_types/_regex.js @@ -23,7 +23,7 @@ describe('Regex', function () { describe('constructor', function () { it('should be an instance of BaseAggParam', function () { - let aggParam = new RegexAggParam({ + const aggParam = new RegexAggParam({ name: 'some_param', type: 'regex' }); @@ -36,11 +36,11 @@ describe('Regex', function () { describe('write results', function () { let aggParam; let aggConfig; - let output = { params: {} }; - let paramName = 'exclude'; + const output = { params: {} }; + const paramName = 'exclude'; beforeEach(function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'terms', schema: 'split', params: { field: 'extension' }}, diff --git a/src/ui/public/agg_types/__tests__/param_types/_string.js b/src/ui/public/agg_types/__tests__/param_types/_string.js index fde04e53a2742..01de3883c115c 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_string.js +++ b/src/ui/public/agg_types/__tests__/param_types/_string.js @@ -5,7 +5,7 @@ import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; import AggTypesParamTypesStringProvider from 'ui/agg_types/param_types/string'; module.exports = describe('String', function () { - let paramName = 'json_test'; + const paramName = 'json_test'; let BaseAggParam; let StringAggParam; let aggParam; @@ -14,7 +14,7 @@ module.exports = describe('String', function () { function initAggParam(config) { config = config || {}; - let defaults = { + const defaults = { name: paramName, type: 'string' }; @@ -42,8 +42,8 @@ module.exports = describe('String', function () { describe('write', function () { it('should append param by name', function () { - let paramName = 'testing'; - let params = {}; + const paramName = 'testing'; + const params = {}; params[paramName] = 'some input'; initAggParam({ name: paramName }); @@ -55,8 +55,8 @@ module.exports = describe('String', function () { }); it('should not be in output with empty input', function () { - let paramName = 'more_testing'; - let params = {}; + const paramName = 'more_testing'; + const params = {}; params[paramName] = ''; initAggParam({ name: paramName }); diff --git a/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js b/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js index c12ced529cf5f..8fdab2c7c66ad 100644 --- a/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js +++ b/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import sinon from 'auto-release-sinon'; function ParamClassStub(parent, body) { - let stub = sinon.spy(body || function () { + const stub = sinon.spy(body || function () { stub.Super && stub.Super.call(this); }); if (parent) _.class(stub).inherits(parent); @@ -24,7 +24,7 @@ function ParamClassStub(parent, body) { * @return {undefined} */ module.exports = function stubParamClasses(Private) { - let BaseAggParam = Private.stub( + const BaseAggParam = Private.stub( require('ui/agg_types/param_types/base'), new ParamClassStub(null, function (config) { _.assign(this, config); diff --git a/src/ui/public/agg_types/agg_params.js b/src/ui/public/agg_types/agg_params.js index d6c435c214b4c..22e85cf12a73a 100644 --- a/src/ui/public/agg_types/agg_params.js +++ b/src/ui/public/agg_types/agg_params.js @@ -10,7 +10,7 @@ import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function AggParamsFactory(Private) { - let paramTypeMap = { + const paramTypeMap = { field: Private(AggTypesParamTypesFieldProvider), optioned: Private(AggTypesParamTypesOptionedProvider), regex: Private(AggTypesParamTypesRegexProvider), @@ -37,8 +37,8 @@ export default function AggParamsFactory(Private) { AggParams.Super.call(this, { index: ['name'], initialSet: params.map(function (config) { - let type = config.name === 'field' ? config.name : config.type; - let Class = paramTypeMap[type] || paramTypeMap._default; + const type = config.name === 'field' ? config.name : config.type; + const Class = paramTypeMap[type] || paramTypeMap._default; return new Class(config); }) }); @@ -59,7 +59,7 @@ export default function AggParamsFactory(Private) { * are dependent on the AggParam#write methods which should be studied for each AggType. */ AggParams.prototype.write = function (aggConfig, locals) { - let output = { params: {} }; + const output = { params: {} }; locals = locals || {}; this.forEach(function (param) { diff --git a/src/ui/public/agg_types/agg_type.js b/src/ui/public/agg_types/agg_type.js index 64f9db58e33e9..ae08206e14948 100644 --- a/src/ui/public/agg_types/agg_type.js +++ b/src/ui/public/agg_types/agg_type.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import AggTypesAggParamsProvider from 'ui/agg_types/agg_params'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeFactory(Private) { - let AggParams = Private(AggTypesAggParamsProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const AggParams = Private(AggTypesAggParamsProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); /** * Generic AggType Constructor @@ -142,7 +142,7 @@ export default function AggTypeFactory(Private) { * @return {FieldFromat} */ AggType.prototype.getFormat = function (agg) { - let field = agg.field(); + const field = agg.field(); return field ? field.format : fieldFormats.getDefaultInstance('string'); }; diff --git a/src/ui/public/agg_types/buckets/_bucket_agg_type.js b/src/ui/public/agg_types/buckets/_bucket_agg_type.js index 4249ec29be71e..7f125455906e9 100644 --- a/src/ui/public/agg_types/buckets/_bucket_agg_type.js +++ b/src/ui/public/agg_types/buckets/_bucket_agg_type.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; export default function BucketAggTypeProvider(Private) { - let AggType = Private(AggTypesAggTypeProvider); + const AggType = Private(AggTypesAggTypeProvider); _.class(BucketAggType).inherits(AggType); function BucketAggType(config) { diff --git a/src/ui/public/agg_types/buckets/_bucket_count_between.js b/src/ui/public/agg_types/buckets/_bucket_count_between.js index 3fbcd3e723343..2838c8397b8e9 100644 --- a/src/ui/public/agg_types/buckets/_bucket_count_between.js +++ b/src/ui/public/agg_types/buckets/_bucket_count_between.js @@ -13,19 +13,19 @@ export default function BucketCountBetweenProvider() { * @return {null|number} */ function bucketCountBetween(aggConfigA, aggConfigB) { - let aggs = aggConfigA.vis.aggs.getRequestAggs(); + const aggs = aggConfigA.vis.aggs.getRequestAggs(); - let aIndex = aggs.indexOf(aggConfigA); - let bIndex = aggs.indexOf(aggConfigB); + const aIndex = aggs.indexOf(aggConfigA); + const bIndex = aggs.indexOf(aggConfigB); if (aIndex === -1 || bIndex === -1) { return null; } // return a negative distance, if b is before a - let negative = (aIndex > bIndex); + const negative = (aIndex > bIndex); - let count = aggs + const count = aggs .slice(Math.min(aIndex, bIndex), Math.max(aIndex, bIndex)) .reduce(function (count, cfg) { if (cfg === aggConfigA || cfg === aggConfigB || cfg.schema.group !== 'buckets') { diff --git a/src/ui/public/agg_types/buckets/_interval_options.js b/src/ui/public/agg_types/buckets/_interval_options.js index f1a8f151898d2..1a5dcd7da8dd9 100644 --- a/src/ui/public/agg_types/buckets/_interval_options.js +++ b/src/ui/public/agg_types/buckets/_interval_options.js @@ -3,7 +3,7 @@ import 'ui/directives/input_whole_number'; export default function IntervalOptionsService(Private) { // shorthand - let ms = function (type) { return moment.duration(1, type).asMilliseconds(); }; + const ms = function (type) { return moment.duration(1, type).asMilliseconds(); }; return [ { diff --git a/src/ui/public/agg_types/buckets/create_filter/date_histogram.js b/src/ui/public/agg_types/buckets/create_filter/date_histogram.js index 67b23bbf2e945..2e3f1dc1f0464 100644 --- a/src/ui/public/agg_types/buckets/create_filter/date_histogram.js +++ b/src/ui/public/agg_types/buckets/create_filter/date_histogram.js @@ -3,8 +3,8 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createDateHistogramFilterProvider(Private) { return function (agg, key) { - let start = moment(key); - let interval = agg.buckets.getInterval(); + const start = moment(key); + const interval = agg.buckets.getInterval(); return buildRangeFilter(agg.params.field, { gte: start.valueOf(), diff --git a/src/ui/public/agg_types/buckets/create_filter/date_range.js b/src/ui/public/agg_types/buckets/create_filter/date_range.js index 89e8232b6e53e..ac44be29de4b7 100644 --- a/src/ui/public/agg_types/buckets/create_filter/date_range.js +++ b/src/ui/public/agg_types/buckets/create_filter/date_range.js @@ -4,9 +4,9 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createDateRangeFilterProvider(config) { return function (agg, key) { - let range = dateRange.parse(key, config.get('dateFormat')); + const range = dateRange.parse(key, config.get('dateFormat')); - let filter = {}; + const filter = {}; if (range.from) filter.gte = +range.from; if (range.to) filter.lt = +range.to; if (range.to && range.from) filter.format = 'epoch_millis'; diff --git a/src/ui/public/agg_types/buckets/create_filter/filters.js b/src/ui/public/agg_types/buckets/create_filter/filters.js index e9cbde979f2f8..da1726ffbf330 100644 --- a/src/ui/public/agg_types/buckets/create_filter/filters.js +++ b/src/ui/public/agg_types/buckets/create_filter/filters.js @@ -3,8 +3,8 @@ import _ from 'lodash'; export default function CreateFilterFiltersProvider(Private) { return function (aggConfig, key) { // have the aggConfig write agg dsl params - let dslFilters = _.get(aggConfig.toDsl(), 'filters.filters'); - let filter = dslFilters[key]; + const dslFilters = _.get(aggConfig.toDsl(), 'filters.filters'); + const filter = dslFilters[key]; if (filter) { return buildQueryFilter(filter.query, aggConfig.vis.indexPattern.id); diff --git a/src/ui/public/agg_types/buckets/create_filter/histogram.js b/src/ui/public/agg_types/buckets/create_filter/histogram.js index fd6c8c1e21c16..30c828b7a4567 100644 --- a/src/ui/public/agg_types/buckets/create_filter/histogram.js +++ b/src/ui/public/agg_types/buckets/create_filter/histogram.js @@ -2,7 +2,7 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createHistogramFilterProvider(Private) { return function (aggConfig, key) { - let value = parseInt(key, 10); + const value = parseInt(key, 10); return buildRangeFilter( aggConfig.params.field, diff --git a/src/ui/public/agg_types/buckets/create_filter/ip_range.js b/src/ui/public/agg_types/buckets/create_filter/ip_range.js index ea5efa64adc34..27fc0650ebb95 100644 --- a/src/ui/public/agg_types/buckets/create_filter/ip_range.js +++ b/src/ui/public/agg_types/buckets/create_filter/ip_range.js @@ -6,7 +6,7 @@ export default function createIpRangeFilterProvider() { if (aggConfig.params.ipRangeType === 'mask') { range = new CidrMask(key).getRange(); } else { - let addresses = key.split(/\-/); + const addresses = key.split(/\-/); range = { from: addresses[0], to: addresses[1] diff --git a/src/ui/public/agg_types/buckets/date_range.js b/src/ui/public/agg_types/buckets/date_range.js index 1101cc72b4398..8f843ba5acbce 100644 --- a/src/ui/public/agg_types/buckets/date_range.js +++ b/src/ui/public/agg_types/buckets/date_range.js @@ -7,9 +7,9 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import dateRangesTemplate from 'ui/agg_types/controls/date_ranges.html'; export default function DateRangeAggDefinition(Private, config) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterDateRangeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterDateRangeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new BucketAggType({ @@ -17,7 +17,7 @@ export default function DateRangeAggDefinition(Private, config) { title: 'Date Range', createFilter: createFilter, getKey: function (bucket, key, agg) { - let formatter = agg.fieldOwnFormatter('text', fieldFormats.getDefaultInstance('date')); + const formatter = agg.fieldOwnFormatter('text', fieldFormats.getDefaultInstance('date')); return dateRange.toString(bucket, formatter); }, getFormat: function () { diff --git a/src/ui/public/agg_types/buckets/filters.js b/src/ui/public/agg_types/buckets/filters.js index 47ab9c13bd0c7..85ad336b4c023 100644 --- a/src/ui/public/agg_types/buckets/filters.js +++ b/src/ui/public/agg_types/buckets/filters.js @@ -5,10 +5,10 @@ import AggTypesBucketsCreateFilterFiltersProvider from 'ui/agg_types/buckets/cre import DecorateQueryProvider from 'ui/courier/data_source/_decorate_query'; import filtersTemplate from 'ui/agg_types/controls/filters.html'; export default function FiltersAggDefinition(Private, Notifier) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterFiltersProvider); - let decorateQuery = Private(DecorateQueryProvider); - let notif = new Notifier({ location: 'Filters Agg' }); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterFiltersProvider); + const decorateQuery = Private(DecorateQueryProvider); + const notif = new Notifier({ location: 'Filters Agg' }); return new BucketAggType({ name: 'filters', @@ -21,25 +21,25 @@ export default function FiltersAggDefinition(Private, Notifier) { editor: filtersTemplate, default: [ {input: {}, label: ''} ], write: function (aggConfig, output) { - let inFilters = aggConfig.params.filters; + const inFilters = aggConfig.params.filters; if (!_.size(inFilters)) return; - let outFilters = _.transform(inFilters, function (filters, filter) { - let input = filter.input; + const outFilters = _.transform(inFilters, function (filters, filter) { + const input = filter.input; if (!input) return notif.log('malformed filter agg params, missing "input" query'); - let query = input.query; + const query = input.query; if (!query) return notif.log('malformed filter agg params, missing "query" on input'); decorateQuery(query); - let label = filter.label || _.get(query, 'query_string.query') || angular.toJson(query); + const label = filter.label || _.get(query, 'query_string.query') || angular.toJson(query); filters[label] = input; }, {}); if (!_.size(outFilters)) return; - let params = output.params || (output.params = {}); + const params = output.params || (output.params = {}); params.filters = outFilters; } } diff --git a/src/ui/public/agg_types/buckets/geo_hash.js b/src/ui/public/agg_types/buckets/geo_hash.js index 230683f4514a2..14c58da476003 100644 --- a/src/ui/public/agg_types/buckets/geo_hash.js +++ b/src/ui/public/agg_types/buckets/geo_hash.js @@ -11,7 +11,7 @@ export default function GeoHashAggDefinition(Private, config) { * Map Leaflet zoom levels to geohash precision levels. * The size of a geohash column-width on the map should be at least `minGeohashPixels` pixels wide. */ - let zoomPrecision = {}; + const zoomPrecision = {}; const minGeohashPixels = 16; for (let zoom = 0; zoom <= 21; zoom += 1) { const worldPixels = 256 * Math.pow(2, zoom); diff --git a/src/ui/public/agg_types/buckets/histogram.js b/src/ui/public/agg_types/buckets/histogram.js index bbfd761b15228..647ae2a6d9f89 100644 --- a/src/ui/public/agg_types/buckets/histogram.js +++ b/src/ui/public/agg_types/buckets/histogram.js @@ -7,8 +7,8 @@ import intervalTemplate from 'ui/agg_types/controls/interval.html'; import minDocCountTemplate from 'ui/agg_types/controls/min_doc_count.html'; import extendedBoundsTemplate from 'ui/agg_types/controls/extended_bounds.html'; export default function HistogramAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterHistogramProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterHistogramProvider); return new BucketAggType({ @@ -49,7 +49,7 @@ export default function HistogramAggDefinition(Private) { default: {}, editor: extendedBoundsTemplate, write: function (aggConfig, output) { - let val = aggConfig.params.extended_bounds; + const val = aggConfig.params.extended_bounds; if (aggConfig.params.min_doc_count && (val.min != null || val.max != null)) { output.params.extended_bounds = { @@ -61,7 +61,7 @@ export default function HistogramAggDefinition(Private) { // called from the editor shouldShow: function (aggConfig) { - let field = aggConfig.params.field; + const field = aggConfig.params.field; if ( field && (field.type === 'number' || field.type === 'date') diff --git a/src/ui/public/agg_types/buckets/ip_range.js b/src/ui/public/agg_types/buckets/ip_range.js index ea1a446101625..7d4e8906445ab 100644 --- a/src/ui/public/agg_types/buckets/ip_range.js +++ b/src/ui/public/agg_types/buckets/ip_range.js @@ -6,8 +6,8 @@ import AggTypesBucketsCreateFilterIpRangeProvider from 'ui/agg_types/buckets/cre import ipRangesTemplate from 'ui/agg_types/controls/ip_ranges.html'; export default function RangeAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterIpRangeProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterIpRangeProvider); return new BucketAggType({ name: 'ip_range', @@ -38,7 +38,7 @@ export default function RangeAggDefinition(Private) { }, editor: ipRangesTemplate, write: function (aggConfig, output) { - let ipRangeType = aggConfig.params.ipRangeType; + const ipRangeType = aggConfig.params.ipRangeType; output.params.ranges = aggConfig.params.ranges[ipRangeType]; } } diff --git a/src/ui/public/agg_types/buckets/range.js b/src/ui/public/agg_types/buckets/range.js index ec6d33935b7c8..9530dfd8e2c4f 100644 --- a/src/ui/public/agg_types/buckets/range.js +++ b/src/ui/public/agg_types/buckets/range.js @@ -5,13 +5,13 @@ import IndexPatternsFieldFormatFieldFormatProvider from 'ui/index_patterns/_fiel import RangeKeyProvider from './range_key'; import rangesTemplate from 'ui/agg_types/controls/ranges.html'; export default function RangeAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterRangeProvider); - let FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); - let RangeKey = Private(RangeKeyProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterRangeProvider); + const FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); + const RangeKey = Private(RangeKeyProvider); - let keyCaches = new WeakMap(); - let formats = new WeakMap(); + const keyCaches = new WeakMap(); + const formats = new WeakMap(); return new BucketAggType({ name: 'range', @@ -28,7 +28,7 @@ export default function RangeAggDefinition(Private) { keyCaches.set(agg, keys); } - let id = RangeKey.idBucket(bucket); + const id = RangeKey.idBucket(bucket); key = keys.get(id); if (!key) { @@ -42,8 +42,8 @@ export default function RangeAggDefinition(Private) { let format = formats.get(agg); if (format) return format; - let RangeFormat = FieldFormat.from(function (range) { - let format = agg.fieldOwnFormatter(); + const RangeFormat = FieldFormat.from(function (range) { + const format = agg.fieldOwnFormatter(); return `${format(range.gte)} to ${format(range.lt)}`; }); diff --git a/src/ui/public/agg_types/buckets/significant_terms.js b/src/ui/public/agg_types/buckets/significant_terms.js index 36fe87d970d8c..ef28f963da0e1 100644 --- a/src/ui/public/agg_types/buckets/significant_terms.js +++ b/src/ui/public/agg_types/buckets/significant_terms.js @@ -3,8 +3,8 @@ import AggTypesBucketsBucketAggTypeProvider from 'ui/agg_types/buckets/_bucket_a import AggTypesBucketsCreateFilterTermsProvider from 'ui/agg_types/buckets/create_filter/terms'; import orderAndSizeTemplate from 'ui/agg_types/controls/order_and_size.html'; export default function SignificantTermsAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); return new BucketAggType({ name: 'significant_terms', diff --git a/src/ui/public/agg_types/buckets/terms.js b/src/ui/public/agg_types/buckets/terms.js index 4a81cbbf939ff..645cc59d673a9 100644 --- a/src/ui/public/agg_types/buckets/terms.js +++ b/src/ui/public/agg_types/buckets/terms.js @@ -7,13 +7,13 @@ import AggTypesBucketsCreateFilterTermsProvider from 'ui/agg_types/buckets/creat import orderAggTemplate from 'ui/agg_types/controls/order_agg.html'; import orderAndSizeTemplate from 'ui/agg_types/controls/order_and_size.html'; export default function TermsAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let bucketCountBetween = Private(AggTypesBucketsBucketCountBetweenProvider); - let AggConfig = Private(VisAggConfigProvider); - let Schemas = Private(VisSchemasProvider); - let createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const bucketCountBetween = Private(AggTypesBucketsBucketCountBetweenProvider); + const AggConfig = Private(VisAggConfigProvider); + const Schemas = Private(VisSchemasProvider); + const createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); - let orderAggSchema = (new Schemas([ + const orderAggSchema = (new Schemas([ { group: 'none', name: 'orderAgg', @@ -24,7 +24,7 @@ export default function TermsAggDefinition(Private) { function isNotType(type) { return function (agg) { - let field = agg.params.field; + const field = agg.params.field; return !field || field.type !== type; }; } @@ -33,7 +33,7 @@ export default function TermsAggDefinition(Private) { name: 'terms', title: 'Terms', makeLabel: function (agg) { - let params = agg.params; + const params = agg.params; return params.field.displayName + ': ' + params.order.display; }, createFilter: createFilter, @@ -73,7 +73,7 @@ export default function TermsAggDefinition(Private) { makeOrderAgg: function (termsAgg, state) { state = state || {}; state.schema = orderAggSchema; - let orderAgg = new AggConfig(termsAgg.vis, state); + const orderAgg = new AggConfig(termsAgg.vis, state); orderAgg.id = termsAgg.id + '-orderAgg'; return orderAgg; }, @@ -86,18 +86,18 @@ export default function TermsAggDefinition(Private) { } }; - let INIT = {}; // flag to know when prevOrderBy has changed + const INIT = {}; // flag to know when prevOrderBy has changed let prevOrderBy = INIT; $scope.$watch('responseValueAggs', updateOrderAgg); $scope.$watch('agg.params.orderBy', updateOrderAgg); function updateOrderAgg() { - let agg = $scope.agg; - let aggs = agg.vis.aggs; - let params = agg.params; - let orderBy = params.orderBy; - let paramDef = agg.type.params.byName.orderAgg; + const agg = $scope.agg; + const aggs = agg.vis.aggs; + const params = agg.params; + const orderBy = params.orderBy; + const paramDef = agg.type.params.byName.orderAgg; // setup the initial value of orderBy if (!orderBy && prevOrderBy === INIT) { @@ -130,9 +130,9 @@ export default function TermsAggDefinition(Private) { } }, write: function (agg, output) { - let vis = agg.vis; - let dir = agg.params.order.val; - let order = output.params.order = {}; + const vis = agg.vis; + const dir = agg.params.order.val; + const order = output.params.order = {}; let orderAgg = agg.params.orderAgg || vis.aggs.getResponseAggById(agg.params.orderBy); @@ -153,7 +153,7 @@ export default function TermsAggDefinition(Private) { return; } - let orderAggId = orderAgg.id; + const orderAggId = orderAgg.id; if (orderAgg.parentId) { orderAgg = vis.aggs.byId[orderAgg.parentId]; } diff --git a/src/ui/public/agg_types/index.js b/src/ui/public/agg_types/index.js index 762a9dbab4a99..ad7af3709460e 100644 --- a/src/ui/public/agg_types/index.js +++ b/src/ui/public/agg_types/index.js @@ -21,7 +21,7 @@ import AggTypesBucketsSignificantTermsProvider from 'ui/agg_types/buckets/signif import AggTypesBucketsGeoHashProvider from 'ui/agg_types/buckets/geo_hash'; export default function AggTypeService(Private) { - let aggs = { + const aggs = { metrics: [ Private(AggTypesMetricsCountProvider), Private(AggTypesMetricsAvgProvider), diff --git a/src/ui/public/agg_types/metrics/avg.js b/src/ui/public/agg_types/metrics/avg.js index f313464433da1..1550fc964fc5b 100644 --- a/src/ui/public/agg_types/metrics/avg.js +++ b/src/ui/public/agg_types/metrics/avg.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricAvgProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'avg', diff --git a/src/ui/public/agg_types/metrics/cardinality.js b/src/ui/public/agg_types/metrics/cardinality.js index 8ff6d93f61924..d76f83bcaf8df 100644 --- a/src/ui/public/agg_types/metrics/cardinality.js +++ b/src/ui/public/agg_types/metrics/cardinality.js @@ -2,8 +2,8 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeMetricCardinalityProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new MetricAggType({ name: 'cardinality', diff --git a/src/ui/public/agg_types/metrics/count.js b/src/ui/public/agg_types/metrics/count.js index fcad3d8dffa06..2e76b8fc5c2d3 100644 --- a/src/ui/public/agg_types/metrics/count.js +++ b/src/ui/public/agg_types/metrics/count.js @@ -2,8 +2,8 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeMetricCountProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new MetricAggType({ name: 'count', diff --git a/src/ui/public/agg_types/metrics/get_response_agg_config_class.js b/src/ui/public/agg_types/metrics/get_response_agg_config_class.js index b9112f343e81b..07a54b2366b64 100644 --- a/src/ui/public/agg_types/metrics/get_response_agg_config_class.js +++ b/src/ui/public/agg_types/metrics/get_response_agg_config_class.js @@ -30,7 +30,7 @@ export default function ResponseAggConfigProvider() { this.key = key; this.parentId = this.id; - let subId = String(key); + const subId = String(key); if (subId.indexOf('.') > -1) { this.id = this.parentId + '[\'' + subId.replace(/'/g, '\\\'') + '\']'; } else { diff --git a/src/ui/public/agg_types/metrics/max.js b/src/ui/public/agg_types/metrics/max.js index 938ee8d4a45e7..b360a2b5dac75 100644 --- a/src/ui/public/agg_types/metrics/max.js +++ b/src/ui/public/agg_types/metrics/max.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricMaxProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'max', diff --git a/src/ui/public/agg_types/metrics/median.js b/src/ui/public/agg_types/metrics/median.js index 1564aeba278ad..e489f5d28f39e 100644 --- a/src/ui/public/agg_types/metrics/median.js +++ b/src/ui/public/agg_types/metrics/median.js @@ -3,9 +3,9 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import AggTypesMetricsGetResponseAggConfigClassProvider from 'ui/agg_types/metrics/get_response_agg_config_class'; import AggTypesMetricsPercentilesProvider from 'ui/agg_types/metrics/percentiles'; export default function AggTypeMetricMedianProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let percentiles = Private(AggTypesMetricsPercentilesProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const percentiles = Private(AggTypesMetricsPercentilesProvider); return new MetricAggType({ name: 'median', diff --git a/src/ui/public/agg_types/metrics/metric_agg_type.js b/src/ui/public/agg_types/metrics/metric_agg_type.js index e9d03f60f3356..bb39beb086862 100644 --- a/src/ui/public/agg_types/metrics/metric_agg_type.js +++ b/src/ui/public/agg_types/metrics/metric_agg_type.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function MetricAggTypeProvider(Private) { - let AggType = Private(AggTypesAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const AggType = Private(AggTypesAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); _.class(MetricAggType).inherits(AggType); function MetricAggType(config) { @@ -24,7 +24,7 @@ export default function MetricAggTypeProvider(Private) { */ MetricAggType.prototype.getValue = function (agg, bucket) { // Metric types where an empty set equals `zero` - let isSettableToZero = ['cardinality', 'sum'].indexOf(agg.__type.name) !== -1; + const isSettableToZero = ['cardinality', 'sum'].indexOf(agg.__type.name) !== -1; // Return proper values when no buckets are present // `Count` handles empty sets properly @@ -42,7 +42,7 @@ export default function MetricAggTypeProvider(Private) { * @return {FieldFromat} */ MetricAggType.prototype.getFormat = function (agg) { - let field = agg.field(); + const field = agg.field(); return field ? field.format : fieldFormats.getDefaultInstance('number'); }; diff --git a/src/ui/public/agg_types/metrics/min.js b/src/ui/public/agg_types/metrics/min.js index a14593af1dd01..7c1a19dbabaf4 100644 --- a/src/ui/public/agg_types/metrics/min.js +++ b/src/ui/public/agg_types/metrics/min.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricMinProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'min', diff --git a/src/ui/public/agg_types/metrics/percentile_ranks.js b/src/ui/public/agg_types/metrics/percentile_ranks.js index 4400873b2c620..0e057533dcbd5 100644 --- a/src/ui/public/agg_types/metrics/percentile_ranks.js +++ b/src/ui/public/agg_types/metrics/percentile_ranks.js @@ -7,16 +7,16 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import getPercentileValue from './percentiles_get_value'; export default function AggTypeMetricPercentileRanksProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); // required by the values editor - let valueProps = { + const valueProps = { makeLabel: function () { - let field = this.field(); - let format = (field && field.format) || fieldFormats.getDefaultInstance('number'); + const field = this.field(); + const format = (field && field.format) || fieldFormats.getDefaultInstance('number'); const label = this.params.customLabel || this.fieldDisplayName(); return 'Percentile rank ' + format.convert(this.key, 'text') + ' of "' + label + '"'; @@ -46,7 +46,7 @@ export default function AggTypeMetricPercentileRanksProvider(Private) { } ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, valueProps); + const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); return agg.params.values.map(function (value) { return new ValueAggConfig(value); diff --git a/src/ui/public/agg_types/metrics/percentiles.js b/src/ui/public/agg_types/metrics/percentiles.js index 59ba2da34387f..b6ef168db5831 100644 --- a/src/ui/public/agg_types/metrics/percentiles.js +++ b/src/ui/public/agg_types/metrics/percentiles.js @@ -8,13 +8,13 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import getPercentileValue from './percentiles_get_value'; export default function AggTypeMetricPercentilesProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); // required by the percentiles editor - let valueProps = { + const valueProps = { makeLabel: function () { const label = this.params.customLabel || this.fieldDisplayName(); return ordinalSuffix(this.key) + ' percentile of ' + label; @@ -44,7 +44,7 @@ export default function AggTypeMetricPercentilesProvider(Private) { } ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, valueProps); + const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); return agg.params.percents.map(function (percent) { return new ValueAggConfig(percent); diff --git a/src/ui/public/agg_types/metrics/std_deviation.js b/src/ui/public/agg_types/metrics/std_deviation.js index c28b700aed296..8976fedc8af04 100644 --- a/src/ui/public/agg_types/metrics/std_deviation.js +++ b/src/ui/public/agg_types/metrics/std_deviation.js @@ -2,12 +2,12 @@ import _ from 'lodash'; import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; import AggTypesMetricsGetResponseAggConfigClassProvider from 'ui/agg_types/metrics/get_response_agg_config_class'; export default function AggTypeMetricStandardDeviationProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let responseAggConfigProps = { + const responseAggConfigProps = { valProp: function () { - let details = this.keyedDetails(this.params.customLabel)[this.key]; + const details = this.keyedDetails(this.params.customLabel)[this.key]; return details.valProp; }, makeLabel: function () { @@ -45,7 +45,7 @@ export default function AggTypeMetricStandardDeviationProvider(Private) { ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); + const ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); return [ new ValueAggConfig('std_lower'), diff --git a/src/ui/public/agg_types/metrics/sum.js b/src/ui/public/agg_types/metrics/sum.js index d419edb241e65..bca621988a74e 100644 --- a/src/ui/public/agg_types/metrics/sum.js +++ b/src/ui/public/agg_types/metrics/sum.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricSumProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'sum', diff --git a/src/ui/public/agg_types/param_types/field.js b/src/ui/public/agg_types/param_types/field.js index 4b61581b5b419..4ac1d0f8cabb9 100644 --- a/src/ui/public/agg_types/param_types/field.js +++ b/src/ui/public/agg_types/param_types/field.js @@ -4,7 +4,7 @@ import editorHtml from 'ui/agg_types/controls/field.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function FieldAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(FieldAggParam).inherits(BaseAggParam); function FieldAggParam(config) { @@ -33,7 +33,7 @@ export default function FieldAggParamFactory(Private) { * @return {field} */ FieldAggParam.prototype.deserialize = function (fieldName, aggConfig) { - let field = aggConfig.vis.indexPattern.fields.byName[fieldName]; + const field = aggConfig.vis.indexPattern.fields.byName[fieldName]; if (!field) { throw new SavedObjectNotFound('index-pattern-field', fieldName); @@ -53,7 +53,7 @@ export default function FieldAggParamFactory(Private) { * @return {undefined} */ FieldAggParam.prototype.write = function (aggConfig, output) { - let field = aggConfig.params.field; + const field = aggConfig.params.field; if (field.scripted) { output.params.script = { diff --git a/src/ui/public/agg_types/param_types/optioned.js b/src/ui/public/agg_types/param_types/optioned.js index 2e161a879a6c5..7fb0f06bf6c95 100644 --- a/src/ui/public/agg_types/param_types/optioned.js +++ b/src/ui/public/agg_types/param_types/optioned.js @@ -3,7 +3,7 @@ import IndexedArray from 'ui/indexed_array'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function OptionedAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(OptionedAggParam).inherits(BaseAggParam); function OptionedAggParam(config) { diff --git a/src/ui/public/agg_types/param_types/raw_json.js b/src/ui/public/agg_types/param_types/raw_json.js index 25f160174230d..b865b2312c896 100644 --- a/src/ui/public/agg_types/param_types/raw_json.js +++ b/src/ui/public/agg_types/param_types/raw_json.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/raw_json.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function RawJSONAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(RawJSONAggParam).inherits(BaseAggParam); function RawJSONAggParam(config) { @@ -26,7 +26,7 @@ export default function RawJSONAggParamFactory(Private) { */ RawJSONAggParam.prototype.write = function (aggConfig, output) { let paramJSON; - let param = aggConfig.params[this.name]; + const param = aggConfig.params[this.name]; if (!param) { return; @@ -45,7 +45,7 @@ export default function RawJSONAggParamFactory(Private) { .keys() .union(_.keys(b)) .transform(function (dest, key) { - let val = compare(a[key], b[key]); + const val = compare(a[key], b[key]); if (val !== undefined) dest[key] = val; }, {}) .value(); diff --git a/src/ui/public/agg_types/param_types/regex.js b/src/ui/public/agg_types/param_types/regex.js index 3a38c06f8b9da..b00c6f654ea37 100644 --- a/src/ui/public/agg_types/param_types/regex.js +++ b/src/ui/public/agg_types/param_types/regex.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/regular_expression.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function RegexAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(RegexAggParam).inherits(BaseAggParam); function RegexAggParam(config) { @@ -33,15 +33,15 @@ export default function RegexAggParamFactory(Private) { * @return {undefined} */ RegexAggParam.prototype.write = function (aggConfig, output) { - let param = aggConfig.params[this.name]; - let paramType = aggConfig.type.params.byName[this.name]; + const param = aggConfig.params[this.name]; + const paramType = aggConfig.type.params.byName[this.name]; // clear aggParam if pattern is not set or is disabled if (!param || !param.pattern || !param.pattern.length || paramType.disabled(aggConfig)) { return; } - let obj = { + const obj = { pattern: param.pattern }; diff --git a/src/ui/public/agg_types/param_types/string.js b/src/ui/public/agg_types/param_types/string.js index 58803171c44a4..dc15d9eefdbdb 100644 --- a/src/ui/public/agg_types/param_types/string.js +++ b/src/ui/public/agg_types/param_types/string.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/string.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function FieldAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(ScriptAggParam).inherits(BaseAggParam); function ScriptAggParam(config) { diff --git a/src/ui/public/bind/__tests__/bind.js b/src/ui/public/bind/__tests__/bind.js index e7acb9b037080..ad00339c6a033 100644 --- a/src/ui/public/bind/__tests__/bind.js +++ b/src/ui/public/bind/__tests__/bind.js @@ -16,7 +16,7 @@ describe('$scope.$bind', function () { expect($rootScope.$bind).to.be.a('function'); expect($scope).to.have.property('$bind', $rootScope.$bind); - let $isoScope = $scope.$new(true); + const $isoScope = $scope.$new(true); expect($isoScope).to.have.property('$bind', $rootScope.$bind); }); @@ -33,7 +33,7 @@ describe('$scope.$bind', function () { }); it('sets up a binding from the child to the parent scope', function () { - let stub = sinon.stub(); + const stub = sinon.stub(); $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); @@ -47,8 +47,8 @@ describe('$scope.$bind', function () { }); it('pulls from the scopes $parent by default', function () { - let $parent = $rootScope.$new(); - let $self = $parent.$new(); + const $parent = $rootScope.$new(); + const $self = $parent.$new(); $parent.val = 'foo'; $self.val = 'bar'; @@ -58,8 +58,8 @@ describe('$scope.$bind', function () { }); it('accepts an alternate scope to read from', function () { - let $parent = $rootScope.$new(); - let $self = $parent.$new(); + const $parent = $rootScope.$new(); + const $self = $parent.$new(); $parent.val = 'foo'; $self.val = 'bar'; diff --git a/src/ui/public/bind/bind.js b/src/ui/public/bind/bind.js index ba16ddc5bfdcb..5d8afb8509d25 100644 --- a/src/ui/public/bind/bind.js +++ b/src/ui/public/bind/bind.js @@ -27,19 +27,19 @@ uiModules.get('kibana') * @return {undefined} */ $delegate.constructor.prototype.$bind = function (to, from, $sourceScope) { - let $source = $sourceScope || this.$parent; - let $target = this; + const $source = $sourceScope || this.$parent; + const $target = this; // parse expressions - let $to = $parse(to); + const $to = $parse(to); if (!$to.assign) errorNotAssignable(to, from); - let $from = $parse(from); + const $from = $parse(from); // bind scopes to expressions - let getTarget = function () { return $to($target); }; - let setTarget = function (v) { return $to.assign($target, v); }; - let getSource = function () { return $from($source); }; - let setSource = function (v) { return $from.assignOrFail($source, v); }; + const getTarget = function () { return $to($target); }; + const setTarget = function (v) { return $to.assign($target, v); }; + const getSource = function () { return $from($source); }; + const setSource = function (v) { return $from.assignOrFail($source, v); }; // to support writing from the child to the parent we need to know // which source has changed. Track the source value and anytime it @@ -55,19 +55,19 @@ uiModules.get('kibana') }; // if we are syncing down a literal, then we use loose equality check - let strict = !$from.literal; - let compare = strict ? strictEquality : angular.equals; + const strict = !$from.literal; + const compare = strict ? strictEquality : angular.equals; // push the initial value down, start off in sync setTarget(lastSourceVal); $target.$watch(function () { - let sourceVal = getSource(); - let targetVal = getTarget(); + const sourceVal = getSource(); + const targetVal = getTarget(); - let outOfSync = !compare(sourceVal, targetVal); - let sourceChanged = outOfSync && !compare(sourceVal, lastSourceVal); + const outOfSync = !compare(sourceVal, targetVal); + const sourceChanged = outOfSync && !compare(sourceVal, lastSourceVal); if (sourceChanged) setTarget(sourceVal); else if (outOfSync) setSource(targetVal); diff --git a/src/ui/public/binder/__tests__/binder.js b/src/ui/public/binder/__tests__/binder.js index 182050bb597fd..97d518a6008d9 100644 --- a/src/ui/public/binder/__tests__/binder.js +++ b/src/ui/public/binder/__tests__/binder.js @@ -16,13 +16,13 @@ describe('Binder class', function () { context('Constructing with a $scope', function () { it('accepts a $scope and listens for $destroy', function () { sinon.stub($scope, '$on'); - let binder = new Binder($scope); + const binder = new Binder($scope); expect($scope.$on.callCount).to.be(1); expect($scope.$on.args[0][0]).to.be('$destroy'); }); it('unbinds when the $scope is destroyed', function () { - let binder = new Binder($scope); + const binder = new Binder($scope); sinon.stub(binder, 'destroy'); $scope.$destroy(); expect(binder.destroy.callCount).to.be(1); @@ -31,12 +31,12 @@ describe('Binder class', function () { describe('Binder#on', function () { it('binds to normal event emitters', function () { - let binder = new Binder(); - let emitter = { + const binder = new Binder(); + const emitter = { on: sinon.stub(), removeListener: sinon.stub() }; - let handler = sinon.stub(); + const handler = sinon.stub(); binder.on(emitter, 'click', handler); expect(emitter.on.callCount).to.be(1); @@ -52,9 +52,9 @@ describe('Binder class', function () { describe('Binder#jqOn', function () { it('binds jquery event handlers', function () { - let binder = new Binder(); - let el = document.createElement('div'); - let handler = sinon.stub(); + const binder = new Binder(); + const el = document.createElement('div'); + const handler = sinon.stub(); binder.jqOn(el, 'click', handler); $(el).click(); diff --git a/src/ui/public/chrome/__tests__/nav_controls.js b/src/ui/public/chrome/__tests__/nav_controls.js index dda0bdc483465..921ee5e7710f9 100644 --- a/src/ui/public/chrome/__tests__/nav_controls.js +++ b/src/ui/public/chrome/__tests__/nav_controls.js @@ -36,7 +36,7 @@ describe('chrome nav controls', function () { }; }); - let $el = compile(); + const $el = compile(); expect($el.find('#testTemplateEl')).to.have.length(1); }); @@ -63,7 +63,7 @@ describe('chrome nav controls', function () { }; }); - let $el = compile(); + const $el = compile(); expect( $el.find('.testControl') .toArray() diff --git a/src/ui/public/chrome/api/angular.js b/src/ui/public/chrome/api/angular.js index e8f9b30115e6b..945c97ee54d5e 100644 --- a/src/ui/public/chrome/api/angular.js +++ b/src/ui/public/chrome/api/angular.js @@ -13,7 +13,7 @@ module.exports = function (chrome, internals) { chrome.getBreadcrumbs = _.noop; chrome.setupAngular = function () { - let kibana = modules.get('kibana'); + const kibana = modules.get('kibana'); _.forOwn(chrome.getInjected(), function (val, name) { kibana.value(name, val); @@ -28,7 +28,7 @@ module.exports = function (chrome, internals) { .value('sessionId', Date.now()) .value('chrome', chrome) .value('esUrl', (function () { - let a = document.createElement('a'); + const a = document.createElement('a'); a.href = chrome.addBasePath('/elasticsearch'); return a.href; }())) @@ -39,7 +39,7 @@ module.exports = function (chrome, internals) { }; chrome.getBreadcrumbs = () => { - let path = $location.path(); + const path = $location.path(); let length = path.length - 1; // trim trailing slash diff --git a/src/ui/public/chrome/api/nav.js b/src/ui/public/chrome/api/nav.js index f66db80a634e5..b592eaf0eb019 100644 --- a/src/ui/public/chrome/api/nav.js +++ b/src/ui/public/chrome/api/nav.js @@ -19,10 +19,10 @@ export default function (chrome, internals) { }; chrome.addBasePath = function (url) { - let isUrl = url && isString(url); + const isUrl = url && isString(url); if (!isUrl) return url; - let parsed = parse(url, true, true); + const parsed = parse(url, true, true); if (!parsed.host && parsed.pathname) { if (parsed.pathname[0] === '/') { parsed.pathname = chrome.getBasePath() + parsed.pathname; @@ -126,7 +126,7 @@ export default function (chrome, internals) { internals.nav.forEach(link => { // convert all link urls to absolute urls - let a = document.createElement('a'); + const a = document.createElement('a'); a.setAttribute('href', link.url); link.url = a.href; }); diff --git a/src/ui/public/chrome/api/theme.js b/src/ui/public/chrome/api/theme.js index 192239cd91488..f2fee099ad015 100644 --- a/src/ui/public/chrome/api/theme.js +++ b/src/ui/public/chrome/api/theme.js @@ -81,8 +81,8 @@ module.exports = function (chrome, internals) { * @return {chrome} */ chrome.removeApplicationClass = function (val) { - let classesToRemove = [].concat(val || []); - let classes = internals.applicationClasses || []; + const classesToRemove = [].concat(val || []); + const classes = internals.applicationClasses || []; _.pull(classes, ...classesToRemove); internals.applicationClasses = classes; diff --git a/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js b/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js index 3f0dac3370d89..19c8d7f62a732 100644 --- a/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js +++ b/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js @@ -18,7 +18,7 @@ describe('appSwitcher directive', function () { function setup(href, links) { return ngMock.inject(function ($window, $rootScope, $compile, Private) { - let domLocation = Private(DomLocationProvider); + const domLocation = Private(DomLocationProvider); $rootScope.chrome = { getNavLinks: constant(cloneDeep(links)), @@ -46,14 +46,14 @@ describe('appSwitcher directive', function () { } context('when one link is for the active app', function () { - let myLink = { + const myLink = { active: true, title: 'myLink', url: 'http://localhost:555/app/myApp', lastSubUrl: 'http://localhost:555/app/myApp#/lastSubUrl' }; - let notMyLink = { + const notMyLink = { active: false, title: 'notMyLink', url: 'http://localhost:555/app/notMyApp', @@ -63,27 +63,27 @@ describe('appSwitcher directive', function () { beforeEach(setup('http://localhost:5555/app/myApp/', [myLink, notMyLink])); it('links to the inactive apps base url', function () { - let $myLink = env.$el.findTestSubject('appLink').eq(0); + const $myLink = env.$el.findTestSubject('appLink').eq(0); expect($myLink.prop('href')).to.be(myLink.url); expect($myLink.prop('href')).to.not.be(myLink.lastSubUrl); }); it('links to the inactive apps last sub url', function () { - let $notMyLink = env.$el.findTestSubject('appLink').eq(1); + const $notMyLink = env.$el.findTestSubject('appLink').eq(1); expect($notMyLink.prop('href')).to.be(notMyLink.lastSubUrl); expect($notMyLink.prop('href')).to.not.be(notMyLink.url); }); }); context('when none of the links are for the active app', function () { - let myLink = { + const myLink = { active: false, title: 'myLink', url: 'http://localhost:555/app/myApp', lastSubUrl: 'http://localhost:555/app/myApp#/lastSubUrl' }; - let notMyLink = { + const notMyLink = { active: false, title: 'notMyLink', url: 'http://localhost:555/app/notMyApp', @@ -93,9 +93,9 @@ describe('appSwitcher directive', function () { beforeEach(setup('http://localhost:5555/app/myApp/', [myLink, notMyLink])); it('links to the lastSubUrl for each', function () { - let $links = env.$el.findTestSubject('appLink'); - let $myLink = $links.eq(0); - let $notMyLink = $links.eq(1); + const $links = env.$el.findTestSubject('appLink'); + const $myLink = $links.eq(0); + const $notMyLink = $links.eq(1); expect($myLink.prop('href')).to.be(myLink.lastSubUrl); expect($myLink.prop('href')).to.not.be(myLink.url); @@ -106,19 +106,19 @@ describe('appSwitcher directive', function () { }); context('clicking a link with matching href but missing hash', function () { - let url = 'http://localhost:555/app/myApp?query=1'; + const url = 'http://localhost:555/app/myApp?query=1'; beforeEach(setup(url + '#/lastSubUrl', [ { url: url } ])); it('just prevents propogation (no reload)', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(url); $link.trigger(event); @@ -129,19 +129,19 @@ describe('appSwitcher directive', function () { }); context('clicking a link that matches entire url', function () { - let url = 'http://localhost:555/app/myApp#/lastSubUrl'; + const url = 'http://localhost:555/app/myApp#/lastSubUrl'; beforeEach(setup(url, [ { url: url } ])); it('calls window.location.reload and prevents propogation', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(env.currentHref); $link.trigger(event); @@ -152,21 +152,21 @@ describe('appSwitcher directive', function () { }); context('clicking a link with matching href but changed hash', function () { - let rootUrl = 'http://localhost:555/app/myApp?query=1'; - let url = rootUrl + '#/lastSubUrl2'; + const rootUrl = 'http://localhost:555/app/myApp?query=1'; + const url = rootUrl + '#/lastSubUrl2'; beforeEach(setup(url + '#/lastSubUrl', [ { url: url } ])); it('calls window.location.reload and prevents propogation', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(url); $link.trigger(event); @@ -185,7 +185,7 @@ describe('appSwitcher directive', function () { ])); it('allows click through', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isPropagationStopped()).to.be(false); @@ -206,7 +206,7 @@ describe('appSwitcher directive', function () { ])); it('allows click through', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isPropagationStopped()).to.be(false); diff --git a/src/ui/public/chrome/directives/kbn_chrome.js b/src/ui/public/chrome/directives/kbn_chrome.js index 3a839f2b9e6b3..9a8376c4fe63d 100644 --- a/src/ui/public/chrome/directives/kbn_chrome.js +++ b/src/ui/public/chrome/directives/kbn_chrome.js @@ -33,7 +33,7 @@ export default function (chrome, internals) { // listen for route changes, propogate to tabs const onRouteChange = function () { - let { href } = window.location; + const { href } = window.location; internals.trackPossibleSubUrl(href); }; diff --git a/src/ui/public/collapsible_sidebar/collapsible_sidebar.js b/src/ui/public/collapsible_sidebar/collapsible_sidebar.js index d19a70af9643e..fb99712ac49f7 100644 --- a/src/ui/public/collapsible_sidebar/collapsible_sidebar.js +++ b/src/ui/public/collapsible_sidebar/collapsible_sidebar.js @@ -8,15 +8,15 @@ uiModules .get('kibana') .directive('collapsibleSidebar', function () { // simply a list of all of all of angulars .col-md-* classes except 12 - let listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); + const listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); return { restrict: 'C', link: function ($scope, $elem) { - let $collapser = $(''); - let $siblings = $elem.siblings(); + const $collapser = $(''); + const $siblings = $elem.siblings(); - let siblingsClass = listOfWidthClasses.reduce(function (prev, className) { + const siblingsClass = listOfWidthClasses.reduce(function (prev, className) { if (prev) return prev; return $siblings.hasClass(className) && className; }, false); diff --git a/src/ui/public/courier/_redirect_when_missing.js b/src/ui/public/courier/_redirect_when_missing.js index b86c75cba4129..5388cb65a879f 100644 --- a/src/ui/public/courier/_redirect_when_missing.js +++ b/src/ui/public/courier/_redirect_when_missing.js @@ -1,9 +1,9 @@ import errors from 'ui/errors'; export default function RedirectWhenMissingFn($location, kbnUrl, Notifier, Promise) { - let SavedObjectNotFound = errors.SavedObjectNotFound; + const SavedObjectNotFound = errors.SavedObjectNotFound; - let notify = new Notifier(); + const notify = new Notifier(); /** * Creates an error handler that will redirect to a url when a SavedObjectNotFound diff --git a/src/ui/public/courier/_request_queue.js b/src/ui/public/courier/_request_queue.js index b6dba26b187f1..b52a8a2fb4be3 100644 --- a/src/ui/public/courier/_request_queue.js +++ b/src/ui/public/courier/_request_queue.js @@ -6,7 +6,7 @@ export default function PendingRequestList() { * they are processed by fetch.[sourceType](). * @type {Array} */ - let queue = []; + const queue = []; queue.getInactive = function (/* strategies */) { return queue.get.apply(queue, arguments) diff --git a/src/ui/public/courier/courier.js b/src/ui/public/courier/courier.js index 4e09d24a8ef82..b489460f8501c 100644 --- a/src/ui/public/courier/courier.js +++ b/src/ui/public/courier/courier.js @@ -24,18 +24,18 @@ import RedirectWhenMissingProvider from './_redirect_when_missing'; uiModules.get('kibana/courier') .service('courier', function ($rootScope, Private, Promise, indexPatterns) { function Courier() { - let self = this; + const self = this; - let DocSource = Private(DocSourceProvider); - let SearchSource = Private(SearchSourceProvider); - let searchStrategy = Private(SearchStrategyProvider); + const DocSource = Private(DocSourceProvider); + const SearchSource = Private(SearchSourceProvider); + const searchStrategy = Private(SearchStrategyProvider); - let requestQueue = Private(RequestQueueProvider); - let errorHandlers = Private(ErrorHandlersProvider); + const requestQueue = Private(RequestQueueProvider); + const errorHandlers = Private(ErrorHandlersProvider); - let fetch = Private(FetchProvider); - let docLooper = self.docLooper = Private(DocLooperProvider); - let searchLooper = self.searchLooper = Private(SearchLooperProvider); + const fetch = Private(FetchProvider); + const docLooper = self.docLooper = Private(DocLooperProvider); + const searchLooper = self.searchLooper = Private(SearchLooperProvider); // expose some internal modules self.setRootSearchSource = Private(RootSearchSourceProvider).set; @@ -47,7 +47,7 @@ uiModules.get('kibana/courier') self.DocSource = DocSource; self.SearchSource = SearchSource; - let HastyRefresh = errors.HastyRefresh; + const HastyRefresh = errors.HastyRefresh; /** * update the time between automatic search requests @@ -135,8 +135,8 @@ uiModules.get('kibana/courier') // Listen for refreshInterval changes $rootScope.$watchCollection('timefilter.refreshInterval', function () { - let refreshValue = _.get($rootScope, 'timefilter.refreshInterval.value'); - let refreshPause = _.get($rootScope, 'timefilter.refreshInterval.pause'); + const refreshValue = _.get($rootScope, 'timefilter.refreshInterval.value'); + const refreshPause = _.get($rootScope, 'timefilter.refreshInterval.pause'); if (_.isNumber(refreshValue) && !refreshPause) { self.fetchInterval(refreshValue); } else { @@ -144,7 +144,7 @@ uiModules.get('kibana/courier') } }); - let onFatalDefer = Promise.defer(); + const onFatalDefer = Promise.defer(); onFatalDefer.promise.then(self.close); Notifier.fatalCallbacks.push(onFatalDefer.resolve); } diff --git a/src/ui/public/courier/data_source/__tests__/decorate_query.js b/src/ui/public/courier/data_source/__tests__/decorate_query.js index adae8151b2dcb..b72146bf8e38e 100644 --- a/src/ui/public/courier/data_source/__tests__/decorate_query.js +++ b/src/ui/public/courier/data_source/__tests__/decorate_query.js @@ -18,7 +18,7 @@ describe('Query decorator', function () { function ($provide) { // Super simple config stub $provide.service('config', function () { - let keys = {}; + const keys = {}; return { get: function (key) { return keys[key]; }, set: function (key, value) { keys[key] = value; } diff --git a/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js b/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js index 061e73e7adfe8..3ab6983a75254 100644 --- a/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js +++ b/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js @@ -24,8 +24,8 @@ describe('SearchSource#normalizeSortRequest', function () { })); it('should return an array', function () { - let sortable = { someField: 'desc'}; - let result = normalizeSortRequest(sortable, indexPattern); + const sortable = { someField: 'desc'}; + const result = normalizeSortRequest(sortable, indexPattern); expect(result).to.be.an(Array); expect(result).to.eql(normalizedSort); // ensure object passed in is not mutated @@ -34,27 +34,27 @@ describe('SearchSource#normalizeSortRequest', function () { }); it('should make plain string sort into the more verbose format', function () { - let result = normalizeSortRequest([{ someField: 'desc'}], indexPattern); + const result = normalizeSortRequest([{ someField: 'desc'}], indexPattern); expect(result).to.eql(normalizedSort); }); it('should append default sort options', function () { - let sortState = [{ + const sortState = [{ someField: { order: 'desc', unmapped_type: 'boolean' } }]; - let result = normalizeSortRequest(sortState, indexPattern); + const result = normalizeSortRequest(sortState, indexPattern); expect(result).to.eql(normalizedSort); }); it('should enable script based sorting', function () { - let fieldName = 'script string'; - let direction = 'desc'; - let indexField = indexPattern.fields.byName[fieldName]; + const fieldName = 'script string'; + const direction = 'desc'; + const indexField = indexPattern.fields.byName[fieldName]; - let sortState = {}; + const sortState = {}; sortState[fieldName] = direction; normalizedSort = { _script: { @@ -76,31 +76,31 @@ describe('SearchSource#normalizeSortRequest', function () { }); it('should use script based sorting only on sortable types', function () { - let fieldName = 'script murmur3'; - let direction = 'asc'; - let indexField = indexPattern.fields.byName[fieldName]; + const fieldName = 'script murmur3'; + const direction = 'asc'; + const indexField = indexPattern.fields.byName[fieldName]; - let sortState = {}; + const sortState = {}; sortState[fieldName] = direction; normalizedSort = {}; normalizedSort[fieldName] = { order: direction, unmapped_type: 'boolean' }; - let result = normalizeSortRequest([sortState], indexPattern); + const result = normalizeSortRequest([sortState], indexPattern); expect(result).to.eql([normalizedSort]); }); it('should remove unmapped_type parameter from _score sorting', function () { - let sortable = { _score: 'desc'}; - let expected = [{ + const sortable = { _score: 'desc'}; + const expected = [{ _score: { order: 'desc' } }]; - let result = normalizeSortRequest(sortable, indexPattern); + const result = normalizeSortRequest(sortable, indexPattern); expect(_.isEqual(result, expected)).to.be.ok(); }); diff --git a/src/ui/public/courier/data_source/_abstract.js b/src/ui/public/courier/data_source/_abstract.js index 4829ef661944a..34680a2c5f679 100644 --- a/src/ui/public/courier/data_source/_abstract.js +++ b/src/ui/public/courier/data_source/_abstract.js @@ -9,12 +9,12 @@ import FetchProvider from '../fetch'; import DecorateQueryProvider from './_decorate_query'; export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) { - let requestQueue = Private(RequestQueueProvider); - let errorHandlers = Private(ErrorHandlersProvider); - let courierFetch = Private(FetchProvider); + const requestQueue = Private(RequestQueueProvider); + const errorHandlers = Private(ErrorHandlersProvider); + const courierFetch = Private(FetchProvider); function SourceAbstract(initialState, strategy) { - let self = this; + const self = this; self._instanceid = _.uniqueId('data_source'); self._state = (function () { @@ -79,7 +79,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * string of the state value to set */ SourceAbstract.prototype.set = function (state, val) { - let self = this; + const self = this; if (typeof state === 'string') { // the getter and setter methods check for undefined explicitly @@ -125,7 +125,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @return {Promise} */ SourceAbstract.prototype.onResults = function (handler) { - let self = this; + const self = this; return new PromiseEmitter(function (resolve, reject) { const defer = Promise.defer(); @@ -149,7 +149,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @return {Promise} */ SourceAbstract.prototype.onError = function (handler) { - let self = this; + const self = this; return new PromiseEmitter(function (resolve, reject) { const defer = Promise.defer(); @@ -172,7 +172,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @async */ SourceAbstract.prototype.fetch = function () { - let self = this; + const self = this; let req = _.first(self._myStartableQueued()); if (!req) { @@ -232,13 +232,13 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @resolved {Object|null} - the flat state of the SourceAbstract */ SourceAbstract.prototype._flatten = function () { - let type = this._getType(); + const type = this._getType(); // the merged state of this dataSource and it's ancestors - let flatState = {}; + const flatState = {}; // function used to write each property from each state object in the chain to flat state - let root = this; + const root = this; // start the chain at this source let current = this; @@ -255,12 +255,12 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) }); } - let prom = root._mergeProp(flatState, value, key); + const prom = root._mergeProp(flatState, value, key); return Promise.is(prom) ? prom : null; })) .then(function () { // move to this sources parent - let parent = current.getParent(); + const parent = current.getParent(); // keep calling until we reach the top parent if (parent) { current = parent; @@ -271,7 +271,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) .then(function () { if (type === 'search') { // This is down here to prevent the circular dependency - let decorateQuery = Private(DecorateQueryProvider); + const decorateQuery = Private(DecorateQueryProvider); flatState.body = flatState.body || {}; @@ -283,7 +283,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) } if (flatState.body.size > 0) { - let computedFields = flatState.index.getComputedFields(); + const computedFields = flatState.index.getComputedFields(); flatState.body.stored_fields = computedFields.storedFields; flatState.body._source = computedFields._source; flatState.body.script_fields = flatState.body.script_fields || {}; @@ -302,7 +302,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * through otherwise it will filter out * @returns {function} */ - let filterNegate = function (reverse) { + const filterNegate = function (reverse) { return function (filter) { if (_.isUndefined(filter.meta) || _.isUndefined(filter.meta.negate)) return !reverse; return filter.meta && filter.meta.negate === reverse; @@ -314,7 +314,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @param {Object} filter - The filter to translate * @return {Object} the query version of that filter */ - let translateToQuery = function (filter) { + const translateToQuery = function (filter) { if (!filter) return; if (filter.query) { @@ -329,7 +329,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @param {object} filter The filter to clean * @returns {object} */ - let cleanFilter = function (filter) { + const cleanFilter = function (filter) { return _.omit(filter, ['meta']); }; diff --git a/src/ui/public/courier/data_source/_decorate_query.js b/src/ui/public/courier/data_source/_decorate_query.js index bb6fca29200b6..d0f009bf0a81c 100644 --- a/src/ui/public/courier/data_source/_decorate_query.js +++ b/src/ui/public/courier/data_source/_decorate_query.js @@ -7,7 +7,7 @@ export default function DecorateQuery(config) { * @returns {object} */ return function (query) { - let queryOptions = config.get('query:queryString:options'); + const queryOptions = config.get('query:queryString:options'); if (_.has(query, 'query_string.query')) { _.extend(query.query_string, queryOptions); diff --git a/src/ui/public/courier/data_source/_doc_send_to_es.js b/src/ui/public/courier/data_source/_doc_send_to_es.js index 5cc07f9e0425e..8204918a30efa 100644 --- a/src/ui/public/courier/data_source/_doc_send_to_es.js +++ b/src/ui/public/courier/data_source/_doc_send_to_es.js @@ -5,8 +5,8 @@ import RequestQueueProvider from 'ui/courier/_request_queue'; import FetchProvider from 'ui/courier/fetch/fetch'; export default function (Promise, Private, es) { - let requestQueue = Private(RequestQueueProvider); - let courierFetch = Private(FetchProvider); + const requestQueue = Private(RequestQueueProvider); + const courierFetch = Private(FetchProvider); /** * Backend for doUpdate and doIndex @@ -16,9 +16,9 @@ export default function (Promise, Private, es) { * @param {String} body - HTTP request body */ return function (method, validateVersion, body, ignore) { - let doc = this; + const doc = this; // straight assignment will causes undefined values - let params = _.pick(this._state, ['id', 'type', 'index']); + const params = _.pick(this._state, ['id', 'type', 'index']); params.body = body; params.ignore = ignore || [409]; @@ -51,13 +51,13 @@ export default function (Promise, Private, es) { // notify pending request for this same document that we have updates docFetchProm.then(function (fetchResp) { // use the key to compair sources - let key = doc._versionKey(); + const key = doc._versionKey(); // clear the queue and filter out the removed items, pushing the // unmatched ones back in. - let respondTo = requestQueue.splice(0).filter(function (req) { - let isDoc = req.source._getType() === 'doc'; - let keyMatches = isDoc && req.source._versionKey() === key; + const respondTo = requestQueue.splice(0).filter(function (req) { + const isDoc = req.source._getType() === 'doc'; + const keyMatches = isDoc && req.source._versionKey() === key; // put some request back into the queue if (!keyMatches) { diff --git a/src/ui/public/courier/data_source/_normalize_sort_request.js b/src/ui/public/courier/data_source/_normalize_sort_request.js index 7bab633bf1d4c..57465b67618d3 100644 --- a/src/ui/public/courier/data_source/_normalize_sort_request.js +++ b/src/ui/public/courier/data_source/_normalize_sort_request.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function normalizeSortRequest(config) { - let defaultSortOptions = config.get('sort:options'); + const defaultSortOptions = config.get('sort:options'); /** * Decorate queries with default parameters @@ -9,7 +9,7 @@ export default function normalizeSortRequest(config) { * @returns {object} */ return function (sortObject, indexPattern) { - let normalizedSort = []; + const normalizedSort = []; // [].concat({}) -> [{}], [].concat([{}]) -> [{}] return [].concat(sortObject).map(function (sortable) { @@ -22,10 +22,10 @@ export default function normalizeSortRequest(config) { { someField: "desc" } into { someField: { "order": "desc"}} */ function normalize(sortable, indexPattern) { - let normalized = {}; + const normalized = {}; let sortField = _.keys(sortable)[0]; let sortValue = sortable[sortField]; - let indexField = indexPattern.fields.byName[sortField]; + const indexField = indexPattern.fields.byName[sortField]; if (indexField && indexField.scripted && indexField.sortable) { let direction; diff --git a/src/ui/public/courier/data_source/_root_search_source.js b/src/ui/public/courier/data_source/_root_search_source.js index c3cb53ffb33c1..634360220326e 100644 --- a/src/ui/public/courier/data_source/_root_search_source.js +++ b/src/ui/public/courier/data_source/_root_search_source.js @@ -1,11 +1,11 @@ import SearchSourceProvider from 'ui/courier/data_source/search_source'; export default function RootSearchSource(Private, $rootScope, timefilter, Notifier) { - let SearchSource = Private(SearchSourceProvider); + const SearchSource = Private(SearchSourceProvider); - let notify = new Notifier({ location: 'Root Search Source' }); + const notify = new Notifier({ location: 'Root Search Source' }); - let globalSource = new SearchSource(); + const globalSource = new SearchSource(); globalSource.inherits(false); // this is the final source, it has no parents globalSource.filter(function (globalSource) { // dynamic time filter will be called in the _flatten phase of things diff --git a/src/ui/public/courier/data_source/doc_source.js b/src/ui/public/courier/data_source/doc_source.js index 67d6de7e9e6b5..2d447d825da68 100644 --- a/src/ui/public/courier/data_source/doc_source.js +++ b/src/ui/public/courier/data_source/doc_source.js @@ -9,10 +9,10 @@ import DocRequestProvider from '../fetch/request/doc'; import DocStrategyProvider from '../fetch/strategy/doc'; export default function DocSourceFactory(Private, Promise, es, sessionStorage) { - let sendToEs = Private(DocSendToEsProvider); - let SourceAbstract = Private(AbstractDataSourceProvider); - let DocRequest = Private(DocRequestProvider); - let docStrategy = Private(DocStrategyProvider); + const sendToEs = Private(DocSendToEsProvider); + const SourceAbstract = Private(AbstractDataSourceProvider); + const DocRequest = Private(DocRequestProvider); + const docStrategy = Private(DocStrategyProvider); _.class(DocSource).inherits(SourceAbstract); function DocSource(initialState) { @@ -99,7 +99,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * @return {string} */ DocSource.prototype._versionKey = function () { - let state = this._state; + const state = this._state; if (!state.index || !state.type || !state.id) return; return 'DocVersion:' + ( @@ -125,10 +125,10 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * @return {[type]} [description] */ DocSource.prototype._getStoredVersion = function () { - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; - let v = sessionStorage.get(key); + const v = sessionStorage.get(key); this._version = v ? _.parseInt(v) : void 0; return this._version; }; @@ -141,7 +141,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { DocSource.prototype._storeVersion = function (version) { if (!version) return this._clearVersion(); - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; this._version = version; sessionStorage.set(key, version); @@ -151,7 +151,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * Clears the stored version for a DocSource */ DocSource.prototype._clearVersion = function () { - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; sessionStorage.remove(key); }; diff --git a/src/ui/public/courier/data_source/search_source.js b/src/ui/public/courier/data_source/search_source.js index ef0fc31ab733c..7db35b4688931 100644 --- a/src/ui/public/courier/data_source/search_source.js +++ b/src/ui/public/courier/data_source/search_source.js @@ -8,11 +8,11 @@ import SegmentedRequestProvider from '../fetch/request/segmented'; import SearchStrategyProvider from '../fetch/strategy/search'; export default function SearchSourceFactory(Promise, Private) { - let SourceAbstract = Private(AbstractDataSourceProvider); - let SearchRequest = Private(SearchRequestProvider); - let SegmentedRequest = Private(SegmentedRequestProvider); - let searchStrategy = Private(SearchStrategyProvider); - let normalizeSortRequest = Private(NormalizeSortRequestProvider); + const SourceAbstract = Private(AbstractDataSourceProvider); + const SearchRequest = Private(SearchRequestProvider); + const SegmentedRequest = Private(SegmentedRequestProvider); + const searchStrategy = Private(SearchStrategyProvider); + const normalizeSortRequest = Private(NormalizeSortRequestProvider); _.class(SearchSource).inherits(SourceAbstract); function SearchSource(initialState) { @@ -71,7 +71,7 @@ export default function SearchSourceFactory(Promise, Private) { * @return {undefined|searchSource} */ SearchSource.prototype.getParent = function (onlyHardLinked) { - let self = this; + const self = this; if (self._parent === false) return; if (self._parent) return self._parent; return onlyHardLinked ? undefined : Private(rootSearchSource).get(); @@ -92,9 +92,9 @@ export default function SearchSourceFactory(Promise, Private) { }; SearchSource.prototype.onBeginSegmentedFetch = function (initFunction) { - let self = this; + const self = this; return Promise.try(function addRequest() { - let req = new SegmentedRequest(self, Promise.defer(), initFunction); + const req = new SegmentedRequest(self, Promise.defer(), initFunction); // return promises created by the completion handler so that // errors will bubble properly @@ -139,7 +139,7 @@ export default function SearchSourceFactory(Promise, Private) { */ SearchSource.prototype._mergeProp = function (state, val, key) { if (typeof val === 'function') { - let source = this; + const source = this; return Promise.cast(val(this)) .then(function (newVal) { return source._mergeProp(state, newVal, key); diff --git a/src/ui/public/courier/looper/_looper.js b/src/ui/public/courier/looper/_looper.js index 8ebf2df44d497..acb769c5f216b 100644 --- a/src/ui/public/courier/looper/_looper.js +++ b/src/ui/public/courier/looper/_looper.js @@ -4,7 +4,7 @@ import 'ui/promises'; import Notifier from 'ui/notify/notifier'; export default function LooperFactory($timeout, Promise) { - let notify = new Notifier(); + const notify = new Notifier(); function Looper(ms, fn) { this._fn = fn; @@ -130,7 +130,7 @@ export default function LooperFactory($timeout, Promise) { * @return {undefined} */ Looper.prototype._loopTheLoop = function () { - let self = this; + const self = this; if (self.active) { self.onHastyLoop(); diff --git a/src/ui/public/courier/looper/doc.js b/src/ui/public/courier/looper/doc.js index e0f21394777c8..1e5363897c513 100644 --- a/src/ui/public/courier/looper/doc.js +++ b/src/ui/public/courier/looper/doc.js @@ -3,15 +3,15 @@ import LooperProvider from './_looper'; import DocStrategyProvider from '../fetch/strategy/doc'; export default function DocLooperService(Private) { - let fetch = Private(FetchProvider); - let Looper = Private(LooperProvider); - let DocStrategy = Private(DocStrategyProvider); + const fetch = Private(FetchProvider); + const Looper = Private(LooperProvider); + const DocStrategy = Private(DocStrategyProvider); /** * The Looper which will manage the doc fetch interval * @type {Looper} */ - let docLooper = new Looper(1500, function () { + const docLooper = new Looper(1500, function () { fetch.fetchQueued(DocStrategy); }); diff --git a/src/ui/public/courier/looper/search.js b/src/ui/public/courier/looper/search.js index ae6867f77d50d..8cd4c895a2972 100644 --- a/src/ui/public/courier/looper/search.js +++ b/src/ui/public/courier/looper/search.js @@ -4,18 +4,18 @@ import RequestQueueProvider from '../_request_queue'; import LooperProvider from './_looper'; export default function SearchLooperService(Private, Promise, Notifier, $rootScope) { - let fetch = Private(FetchProvider); - let searchStrategy = Private(SearchStrategyProvider); - let requestQueue = Private(RequestQueueProvider); + const fetch = Private(FetchProvider); + const searchStrategy = Private(SearchStrategyProvider); + const requestQueue = Private(RequestQueueProvider); - let Looper = Private(LooperProvider); - let notif = new Notifier({ location: 'Search Looper' }); + const Looper = Private(LooperProvider); + const notif = new Notifier({ location: 'Search Looper' }); /** * The Looper which will manage the doc fetch interval * @type {Looper} */ - let searchLooper = new Looper(null, function () { + const searchLooper = new Looper(null, function () { $rootScope.$broadcast('courier:searchRefresh'); return fetch.these( requestQueue.getInactive(searchStrategy) diff --git a/src/ui/public/courier/saved_object/saved_object.js b/src/ui/public/courier/saved_object/saved_object.js index 5c32ccac9064c..32d566e56b8e7 100644 --- a/src/ui/public/courier/saved_object/saved_object.js +++ b/src/ui/public/courier/saved_object/saved_object.js @@ -10,38 +10,38 @@ import SearchSourceProvider from '../data_source/search_source'; export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notifier, safeConfirm, indexPatterns) { - let DocSource = Private(DocSourceProvider); - let SearchSource = Private(SearchSourceProvider); - let mappingSetup = Private(MappingSetupProvider); + const DocSource = Private(DocSourceProvider); + const SearchSource = Private(SearchSourceProvider); + const mappingSetup = Private(MappingSetupProvider); function SavedObject(config) { if (!_.isObject(config)) config = {}; // save an easy reference to this - let self = this; + const self = this; /************ * Initialize config vars ************/ // the doc which is used to store this object - let docSource = new DocSource(); + const docSource = new DocSource(); // type name for this object, used as the ES-type - let type = config.type; + const type = config.type; // Create a notifier for sending alerts - let notify = new Notifier({ + const notify = new Notifier({ location: 'Saved ' + type }); // mapping definition for the fields that this object will expose - let mapping = mappingSetup.expandShorthand(config.mapping); + const mapping = mappingSetup.expandShorthand(config.mapping); // default field values, assigned when the source is loaded - let defaults = config.defaults || {}; + const defaults = config.defaults || {}; - let afterESResp = config.afterESResp || _.noop; - let customInit = config.init || _.noop; + const afterESResp = config.afterESResp || _.noop; + const customInit = config.init || _.noop; // optional search source which this object configures self.searchSource = config.searchSource && new SearchSource(); @@ -113,7 +113,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif if (resp.found != null && !resp.found) throw new errors.SavedObjectNotFound(type, self.id); - let meta = resp._source.kibanaSavedObjectMeta || {}; + const meta = resp._source.kibanaSavedObjectMeta || {}; delete resp._source.kibanaSavedObjectMeta; if (!config.indexPattern && self._source.indexPattern) { @@ -158,8 +158,8 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif state = {}; } - let oldState = self.searchSource.toJSON(); - let fnProps = _.transform(oldState, function (dynamic, val, name) { + const oldState = self.searchSource.toJSON(); + const fnProps = _.transform(oldState, function (dynamic, val, name) { if (_.isFunction(val)) dynamic[name] = val; }, {}); @@ -200,7 +200,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif * @return {Object} */ self.serialize = function () { - let body = {}; + const body = {}; _.forOwn(mapping, function (fieldMapping, fieldName) { if (self[fieldName] != null) { @@ -227,7 +227,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif */ self.save = function () { - let body = self.serialize(); + const body = self.serialize(); // Slugify the object id self.id = slugifyId(self.id); @@ -240,7 +240,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif }; self.saveSource = function (source) { - let finish = function (id) { + const finish = function (id) { self.id = id; return es.indices.refresh({ index: kbnIndex @@ -255,7 +255,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif .catch(function (err) { // record exists, confirm overwriting if (_.get(err, 'origError.status') === 409) { - let confirmMessage = 'Are you sure you want to overwrite ' + self.title + '?'; + const confirmMessage = 'Are you sure you want to overwrite ' + self.title + '?'; return safeConfirm(confirmMessage).then( function () { diff --git a/src/ui/public/debounce/__tests__/debounce.js b/src/ui/public/debounce/__tests__/debounce.js index 5208365c38a8f..9169c76a93568 100644 --- a/src/ui/public/debounce/__tests__/debounce.js +++ b/src/ui/public/debounce/__tests__/debounce.js @@ -27,14 +27,14 @@ describe('debounce service', function () { describe('API', function () { it('should have a cancel method', function () { - let bouncer = debounce(function () {}, 100); + const bouncer = debounce(function () {}, 100); expect(bouncer).to.have.property('cancel'); }); }); describe('delayed execution', function () { it('should delay execution', function () { - let bouncer = debounce(spy, 100); + const bouncer = debounce(spy, 100); bouncer(); expect(spy.callCount).to.be(0); $timeout.flush(); @@ -42,7 +42,7 @@ describe('debounce service', function () { }); it('should fire on leading edge', function () { - let bouncer = debounce(spy, 100, { leading: true }); + const bouncer = debounce(spy, 100, { leading: true }); bouncer(); expect(spy.callCount).to.be(1); $timeout.flush(); @@ -50,7 +50,7 @@ describe('debounce service', function () { }); it('should only fire on leading edge', function () { - let bouncer = debounce(spy, 100, { leading: true, trailing: false }); + const bouncer = debounce(spy, 100, { leading: true, trailing: false }); bouncer(); expect(spy.callCount).to.be(1); $timeout.flush(); @@ -58,8 +58,8 @@ describe('debounce service', function () { }); it('should reset delayed execution', function (done) { - let cancelSpy = sinon.spy($timeout, 'cancel'); - let bouncer = debounce(spy, 100); + const cancelSpy = sinon.spy($timeout, 'cancel'); + const bouncer = debounce(spy, 100); bouncer(); setTimeout(function () { bouncer(); @@ -74,8 +74,8 @@ describe('debounce service', function () { describe('cancel', function () { it('should cancel the $timeout', function () { - let cancelSpy = sinon.spy($timeout, 'cancel'); - let bouncer = debounce(spy, 100); + const cancelSpy = sinon.spy($timeout, 'cancel'); + const bouncer = debounce(spy, 100); bouncer(); bouncer.cancel(); expect(cancelSpy.callCount).to.be(1); diff --git a/src/ui/public/debounce/debounce.js b/src/ui/public/debounce/debounce.js index 7f8652f39d8f5..fc541e108c25e 100644 --- a/src/ui/public/debounce/debounce.js +++ b/src/ui/public/debounce/debounce.js @@ -3,7 +3,7 @@ import uiModules from 'ui/modules'; // Debounce service, angularized version of lodash debounce // borrowed heavily from https://github.com/shahata/angular-debounce -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.service('debounce', ['$timeout', function ($timeout) { return function (func, wait, options) { @@ -20,14 +20,14 @@ module.service('debounce', ['$timeout', function ($timeout) { self = this; args = arguments; - let later = function () { + const later = function () { timeout = null; if (!options.leading || options.trailing) { result = func.apply(self, args); } }; - let callNow = options.leading && !timeout; + const callNow = options.leading && !timeout; if (timeout) { $timeout.cancel(timeout); diff --git a/src/ui/public/directives/__tests__/auto_select_if_only_one.js b/src/ui/public/directives/__tests__/auto_select_if_only_one.js index b414843698b9d..df5103f8d8a28 100644 --- a/src/ui/public/directives/__tests__/auto_select_if_only_one.js +++ b/src/ui/public/directives/__tests__/auto_select_if_only_one.js @@ -7,16 +7,16 @@ import 'ui/directives/auto_select_if_only_one'; describe('Auto-select if only one directive', function () { let $compile; let $rootScope; - let zeroOptions = []; - let oneOption = [{label: 'foo'}]; - let multiOptions = [{label: 'foo'}, {label: 'bar'}]; + const zeroOptions = []; + const oneOption = [{label: 'foo'}]; + const multiOptions = [{label: 'foo'}, {label: 'bar'}]; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; - let html = ''; + const html = ''; $compile(html)($rootScope); $rootScope.value = null; })); @@ -41,7 +41,7 @@ describe('Auto-select if only one directive', function () { it('should still auto select if the collection contains 2 items but is filtered to 1', function () { $rootScope.options = multiOptions; - let html = ''; $compile(html)($rootScope); $rootScope.value = null; diff --git a/src/ui/public/directives/__tests__/confirm-click.js b/src/ui/public/directives/__tests__/confirm-click.js index bdb7e7d62355e..8e0f2aefb3e3e 100644 --- a/src/ui/public/directives/__tests__/confirm-click.js +++ b/src/ui/public/directives/__tests__/confirm-click.js @@ -13,7 +13,7 @@ let $scope; let $elem; -let init = function (text) { +const init = function (text) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/css_truncate.js b/src/ui/public/directives/__tests__/css_truncate.js index 535200bb0abc6..f8a008f13049f 100644 --- a/src/ui/public/directives/__tests__/css_truncate.js +++ b/src/ui/public/directives/__tests__/css_truncate.js @@ -10,7 +10,7 @@ let $scope; let $elem; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/fixed_scroll.js b/src/ui/public/directives/__tests__/fixed_scroll.js index 7bcf4467ab740..b6488caf58a69 100644 --- a/src/ui/public/directives/__tests__/fixed_scroll.js +++ b/src/ui/public/directives/__tests__/fixed_scroll.js @@ -9,7 +9,7 @@ import Promise from 'bluebird'; describe('FixedScroll directive', function () { let compile; - let trash = []; + const trash = []; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($compile, $rootScope) { @@ -19,7 +19,7 @@ describe('FixedScroll directive', function () { // since the directive works at the sibling level we create a // parent for everything to happen in - let $parent = $('
').css({ + const $parent = $('
').css({ position: 'fixed', top: 0, left: 0, @@ -30,12 +30,12 @@ describe('FixedScroll directive', function () { $parent.appendTo(document.body); trash.push($parent); - let $el = $('
').css({ + const $el = $('
').css({ 'overflow-x': 'auto', 'width': $parent.width() }).appendTo($parent); - let $content = $('
').css({ + const $content = $('
').css({ width: $parent.width() * ratioX, height: $parent.height() * ratioY }).appendTo($el); @@ -67,26 +67,26 @@ describe('FixedScroll directive', function () { }); it('attaches a scroller below the element when the content is larger then the container', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller).to.have.length(1); }); it('copies the width of the container', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller.width()).to.be(els.$container.width()); }); it('mimics the scrollWidth of the element', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller.prop('scrollWidth')).to.be(els.$container.prop('scrollWidth')); }); describe('scroll event handling / tug of war prevention', function () { it('listens when needed, unlistens when not needed', function () { - let on = sinon.spy($.fn, 'on'); - let off = sinon.spy($.fn, 'off'); + const on = sinon.spy($.fn, 'on'); + const off = sinon.spy($.fn, 'off'); - let els = compile(1.5); + const els = compile(1.5); expect(on.callCount).to.be(2); checkThisVals('$.fn.on', on); @@ -130,12 +130,12 @@ describe('FixedScroll directive', function () { expect(spy.callCount).to.be(2); // first call should read the scrollLeft from the $container - let firstCall = spy.getCall(0); + const firstCall = spy.getCall(0); expect(firstCall.thisValue.is($from)).to.be(true); expect(firstCall.args).to.eql([]); // second call should be setting the scrollLeft on the $scroller - let secondCall = spy.getCall(1); + const secondCall = spy.getCall(1); expect(secondCall.thisValue.is($to)).to.be(true); expect(secondCall.args).to.eql([firstCall.returnValue]); }); diff --git a/src/ui/public/directives/__tests__/input_focus.js b/src/ui/public/directives/__tests__/input_focus.js index 5d30dbb52f0aa..e6d93ecef387e 100644 --- a/src/ui/public/directives/__tests__/input_focus.js +++ b/src/ui/public/directives/__tests__/input_focus.js @@ -12,7 +12,7 @@ describe('Input focus directive', function () { let $el; let selectedEl; let selectedText; - let inputValue = 'Input Text Value'; + const inputValue = 'Input Text Value'; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (_$compile_, _$rootScope_, _$timeout_) { diff --git a/src/ui/public/directives/__tests__/input_whole_number.js b/src/ui/public/directives/__tests__/input_whole_number.js index 0d97c28dfd767..e52e2aec1abb7 100644 --- a/src/ui/public/directives/__tests__/input_whole_number.js +++ b/src/ui/public/directives/__tests__/input_whole_number.js @@ -6,7 +6,7 @@ import 'ui/directives/input_whole_number'; describe('Whole number input directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -16,7 +16,7 @@ describe('Whole number input directive', function () { })); it('should allow whole numbers', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '123'; $rootScope.$digest(); @@ -32,7 +32,7 @@ describe('Whole number input directive', function () { }); it('should disallow numbers with decimals', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '123.0'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/json_input.js b/src/ui/public/directives/__tests__/json_input.js index b82de486c974c..9ee9cee7df1ad 100644 --- a/src/ui/public/directives/__tests__/json_input.js +++ b/src/ui/public/directives/__tests__/json_input.js @@ -7,7 +7,7 @@ import 'ui/directives/json_input'; describe('JSON input validation', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; let element; beforeEach(ngMock.module('kibana')); @@ -28,8 +28,8 @@ describe('JSON input validation', function () { }); it('should be able to not require keys', function () { - let html = ''; - let element = $compile(html)($rootScope); + const html = ''; + const element = $compile(html)($rootScope); element.val('{}'); element.trigger('input'); diff --git a/src/ui/public/directives/__tests__/paginated_selectable_list.js b/src/ui/public/directives/__tests__/paginated_selectable_list.js index a066d470b4497..30c5f906a5e37 100644 --- a/src/ui/public/directives/__tests__/paginated_selectable_list.js +++ b/src/ui/public/directives/__tests__/paginated_selectable_list.js @@ -3,7 +3,7 @@ import expect from 'expect.js'; import ngMock from 'ng_mock'; import _ from 'lodash'; -let objectList = [ +const objectList = [ { title: 'apple' }, { title: 'orange' }, { title: 'coconut' }, @@ -11,7 +11,7 @@ let objectList = [ { title: 'grapes' } ]; -let stringList = [ +const stringList = [ 'apple', 'orange', 'coconut', @@ -19,18 +19,18 @@ let stringList = [ 'grapes' ]; -let lists = [objectList, stringList, []]; +const lists = [objectList, stringList, []]; let $scope; let $element; let $isolatedScope; lists.forEach(function (list) { - let isArrayOfObjects = list.every((item) => { + const isArrayOfObjects = list.every((item) => { return _.isPlainObject(item); }); - let init = function (arr, willFail) { + const init = function (arr, willFail) { // Load the application ngMock.module('kibana'); @@ -83,8 +83,8 @@ lists.forEach(function (list) { }); it('should initially sort an array of objects in ascending order', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); expect($isolatedScope.hits).to.be.an('array'); @@ -104,8 +104,8 @@ lists.forEach(function (list) { }); it('should sort an array of objects in ascending order', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.isAscending = false; $isolatedScope.sortHits(list); @@ -122,8 +122,8 @@ lists.forEach(function (list) { }); it('should sort an array of objects in descending order', function () { - let property = $isolatedScope.listProperty; - let reversedList = property ? _.sortBy(list, property).reverse() : _.sortBy(list).reverse(); + const property = $isolatedScope.listProperty; + const reversedList = property ? _.sortBy(list, property).reverse() : _.sortBy(list).reverse(); $isolatedScope.isAscending = true; $isolatedScope.sortHits(list); @@ -146,8 +146,8 @@ lists.forEach(function (list) { }); it('should return the result of the function its passed', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.hits.forEach(function (hit, index) { if (property) { @@ -165,8 +165,8 @@ lists.forEach(function (list) { }); it('should return the result of the function its passed', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.userOnSelect = function (val) { return val; }; diff --git a/src/ui/public/directives/__tests__/parse_query.js b/src/ui/public/directives/__tests__/parse_query.js index 6115bbdc20f35..fb2bc7bd13625 100644 --- a/src/ui/public/directives/__tests__/parse_query.js +++ b/src/ui/public/directives/__tests__/parse_query.js @@ -15,13 +15,13 @@ let $elemScope; let $elem; let cycleIndex = 0; -let markup = ''; +const markup = ''; let fromUser; import toUser from 'ui/parse_query/lib/to_user'; import 'ui/parse_query'; import ParseQueryLibFromUserProvider from 'ui/parse_query/lib/from_user'; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -41,7 +41,7 @@ let init = function () { }); }; -let compile = function () { +const compile = function () { $rootScope.mockModel = 'cycle' + cycleIndex++; $rootScope.mockQueryInput = undefined; diff --git a/src/ui/public/directives/__tests__/timepicker.js b/src/ui/public/directives/__tests__/timepicker.js index 46208d5e80cd1..f022f9d37158b 100644 --- a/src/ui/public/directives/__tests__/timepicker.js +++ b/src/ui/public/directives/__tests__/timepicker.js @@ -17,10 +17,10 @@ let $parentScope; let $scope; let $elem; -let anchor = '2014-01-01T06:06:06.666Z'; +const anchor = '2014-01-01T06:06:06.666Z'; let clock; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -34,7 +34,7 @@ let init = function () { $parentScope = $rootScope; // Add some parameters to it - let timefilter = { + const timefilter = { time : { from: moment().subtract(15, 'minutes'), to: moment(), @@ -174,7 +174,7 @@ describe('timepicker directive', function () { expect($elem.find('.kbn-timepicker-modes .active').text().trim()).to.be('quick'); // Each of the 3 modes - let modes = ['absolute', 'relative', 'quick']; + const modes = ['absolute', 'relative', 'quick']; _.each(modes, function (mode) { $scope.setMode(mode); $scope.$digest(); @@ -215,7 +215,7 @@ describe('timepicker directive', function () { }); it('has a preview of the "from" input', function (done) { - let preview = $elem.find('.kbn-timepicker-section span[ng-show="relative.preview"]'); + const preview = $elem.find('.kbn-timepicker-section span[ng-show="relative.preview"]'); expect(preview.text()).to.be(moment().subtract(15, 'minutes').format($scope.format)); done(); }); @@ -226,7 +226,7 @@ describe('timepicker directive', function () { }); it('has a submit handler', function (done) { - let form = $elem.find('form[ng-submit="applyRelative()"]'); + const form = $elem.find('form[ng-submit="applyRelative()"]'); expect(form.length).to.be(1); done(); }); @@ -247,7 +247,7 @@ describe('timepicker directive', function () { }); it('has a dropdown bound to relative.unit that contains all of the intervals', function (done) { - let select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); + const select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); expect(select.length).to.be(1); expect(select.find('option').length).to.be(7); @@ -259,7 +259,7 @@ describe('timepicker directive', function () { }); it('has a checkbox that is checked when rounding is enabled', function (done) { - let checkbox = $elem.find('.kbn-timepicker-section input[ng-model="relative.round"]'); + const checkbox = $elem.find('.kbn-timepicker-section input[ng-model="relative.round"]'); expect(checkbox.length).to.be(1); // Rounding is disabled by default @@ -335,8 +335,8 @@ describe('timepicker directive', function () { }); it('updates the input fields when the scope variables are changed', function (done) { - let input = $elem.find('.kbn-timepicker-section input[ng-model="relative.count"]'); - let select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); + const input = $elem.find('.kbn-timepicker-section input[ng-model="relative.count"]'); + const select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); $scope.relative.count = 5; $scope.$digest(); diff --git a/src/ui/public/directives/__tests__/truncate.js b/src/ui/public/directives/__tests__/truncate.js index 1ed5f4dba3aaf..9132c2bb3b7d1 100644 --- a/src/ui/public/directives/__tests__/truncate.js +++ b/src/ui/public/directives/__tests__/truncate.js @@ -11,7 +11,7 @@ let $scope; let $elem; -let init = function (text) { +const init = function (text) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/typeahead.js b/src/ui/public/directives/__tests__/typeahead.js index 0c7424d356b3b..5e7ca60d896bb 100644 --- a/src/ui/public/directives/__tests__/typeahead.js +++ b/src/ui/public/directives/__tests__/typeahead.js @@ -7,8 +7,8 @@ import 'plugins/kibana/discover/index'; // TODO: This should not be needed, timefilter is only included here, it should move -let typeaheadHistoryCount = 10; -let typeaheadName = 'unittest'; +const typeaheadHistoryCount = 10; +const typeaheadName = 'unittest'; let $parentScope; let $typeaheadScope; let $elem; @@ -20,9 +20,9 @@ let markup = '
' + '' + '' + '
'; -let typeaheadItems = ['abc', 'def', 'ghi']; +const typeaheadItems = ['abc', 'def', 'ghi']; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -64,7 +64,7 @@ let init = function () { describe('typeahead directive', function () { describe('typeahead requirements', function () { describe('missing input', function () { - let goodMarkup = markup; + const goodMarkup = markup; before(function () { markup = '
' + @@ -99,7 +99,7 @@ describe('typeahead directive', function () { }); it('should not save empty entries', function () { - let entries = typeaheadItems.slice(0); + const entries = typeaheadItems.slice(0); entries.push('', 'jkl'); for (let i = 0; i < entries.length; i++) { $typeaheadScope.inputModel.$setViewValue(entries[i]); @@ -129,9 +129,9 @@ describe('typeahead directive', function () { }); it('should order filtered results', function () { - let entries = ['ac/dc', 'anthrax', 'abba', 'phantogram', 'skrillex']; - let allEntries = typeaheadItems.concat(entries); - let startMatches = allEntries.filter(function (item) { + const entries = ['ac/dc', 'anthrax', 'abba', 'phantogram', 'skrillex']; + const allEntries = typeaheadItems.concat(entries); + const startMatches = allEntries.filter(function (item) { return /^a/.test(item); }); typeaheadCtrl.history.add.returns(allEntries); @@ -144,7 +144,7 @@ describe('typeahead directive', function () { typeaheadCtrl.filterItemsByQuery('a'); expect($typeaheadScope.filteredItems).to.contain('phantogram'); - let nonStarterIndex = $typeaheadScope.filteredItems.indexOf('phantogram'); + const nonStarterIndex = $typeaheadScope.filteredItems.indexOf('phantogram'); startMatches.forEach(function (item) { expect($typeaheadScope.filteredItems).to.contain(item); diff --git a/src/ui/public/directives/__tests__/validate_cidr_mask.js b/src/ui/public/directives/__tests__/validate_cidr_mask.js index 702d983ab3b35..6fd8a623d13da 100644 --- a/src/ui/public/directives/__tests__/validate_cidr_mask.js +++ b/src/ui/public/directives/__tests__/validate_cidr_mask.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_cidr_mask'; describe('Validate CIDR mask directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate CIDR mask directive', function () { })); it('should allow empty input', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); @@ -33,7 +33,7 @@ describe('Validate CIDR mask directive', function () { }); it('should allow valid CIDR masks', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '0.0.0.0/1'; $rootScope.$digest(); @@ -53,7 +53,7 @@ describe('Validate CIDR mask directive', function () { }); it('should disallow invalid CIDR masks', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_date_math.js b/src/ui/public/directives/__tests__/validate_date_math.js index 02385b06a4940..869686b5fb1f3 100644 --- a/src/ui/public/directives/__tests__/validate_date_math.js +++ b/src/ui/public/directives/__tests__/validate_date_math.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_date_math'; describe('Validate date math directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate date math directive', function () { })); it('should allow valid date math', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'now'; $rootScope.$digest(); @@ -41,7 +41,7 @@ describe('Validate date math directive', function () { }); it('should disallow invalid date math', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); @@ -61,7 +61,7 @@ describe('Validate date math directive', function () { }); it('should allow empty values', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_index_name.js b/src/ui/public/directives/__tests__/validate_index_name.js index 3deb454077e1e..4bd256ef15a86 100644 --- a/src/ui/public/directives/__tests__/validate_index_name.js +++ b/src/ui/public/directives/__tests__/validate_index_name.js @@ -8,8 +8,8 @@ import 'ui/directives/validate_index_name'; describe('Validate index name directive', function () { let $compile; let $rootScope; - let noWildcardHtml = ''; - let allowWildcardHtml = ''; + const noWildcardHtml = ''; + const allowWildcardHtml = ''; beforeEach(ngMock.module('kibana')); @@ -20,7 +20,7 @@ describe('Validate index name directive', function () { function checkPattern(input, html) { $rootScope.indexName = input; - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.$digest(); return element; } @@ -57,7 +57,7 @@ describe('Validate index name directive', function () { badPatterns.forEach(function (pattern) { it('should not accept index pattern: ' + pattern, function () { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.be(true); expect(element.hasClass('ng-valid')).to.not.be(true); }); @@ -65,7 +65,7 @@ describe('Validate index name directive', function () { goodPatterns.forEach(function (pattern) { it('should accept index pattern: ' + pattern, function () { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.not.be(true); expect(element.hasClass('ng-valid')).to.be(true); }); @@ -73,7 +73,7 @@ describe('Validate index name directive', function () { it('should disallow wildcards by default', function () { wildcardPatterns.forEach(function (pattern) { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.be(true); expect(element.hasClass('ng-valid')).to.not.be(true); }); @@ -81,7 +81,7 @@ describe('Validate index name directive', function () { it('should allow wildcards if the allow-wildcard attribute is present', function () { wildcardPatterns.forEach(function (pattern) { - let element = checkPattern(pattern, allowWildcardHtml); + const element = checkPattern(pattern, allowWildcardHtml); expect(element.hasClass('ng-invalid')).to.not.be(true); expect(element.hasClass('ng-valid')).to.be(true); }); diff --git a/src/ui/public/directives/__tests__/validate_ip.js b/src/ui/public/directives/__tests__/validate_ip.js index 9f5066f28f8cf..6e4e3c65cff64 100644 --- a/src/ui/public/directives/__tests__/validate_ip.js +++ b/src/ui/public/directives/__tests__/validate_ip.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_ip'; describe('Validate IP directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate IP directive', function () { })); it('should allow empty input', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); @@ -33,7 +33,7 @@ describe('Validate IP directive', function () { }); it('should allow valid IP addresses', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '0.0.0.0'; $rootScope.$digest(); @@ -53,7 +53,7 @@ describe('Validate IP directive', function () { }); it('should disallow invalid IP addresses', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_json.js b/src/ui/public/directives/__tests__/validate_json.js index cf2616dc4baf1..69f4ea13d987e 100644 --- a/src/ui/public/directives/__tests__/validate_json.js +++ b/src/ui/public/directives/__tests__/validate_json.js @@ -8,23 +8,23 @@ import 'ui/directives/validate_json'; let $parentScope; let $elemScope; let $elem; -let mockScope = ''; +const mockScope = ''; -let input = { +const input = { valid: '{ "test": "json input" }', invalid: 'strings are not json' }; -let markup = { +const markup = { textarea: '', input: '' }; -let init = function (type) { +const init = function (type) { // Load the application ngMock.module('kibana'); type = type || 'input'; - let elMarkup = markup[type]; + const elMarkup = markup[type]; // Create the scope ngMock.inject(function ($injector, $rootScope, $compile) { @@ -39,7 +39,7 @@ let init = function (type) { }; describe('validate-json directive', function () { - let checkValid = function (inputVal, className) { + const checkValid = function (inputVal, className) { $parentScope.mockModel = inputVal; $elem.scope().$digest(); expect($elem.hasClass(className)).to.be(true); diff --git a/src/ui/public/directives/auto_select_if_only_one.js b/src/ui/public/directives/auto_select_if_only_one.js index 2fead2be3983c..0c77ed7d7150c 100644 --- a/src/ui/public/directives/auto_select_if_only_one.js +++ b/src/ui/public/directives/auto_select_if_only_one.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('autoSelectIfOnlyOne', function ($parse) { return { @@ -7,7 +7,7 @@ module.directive('autoSelectIfOnlyOne', function ($parse) { require: 'ngModel', link: function (scope, element, attributes, ngModelCtrl) { attributes.$observe('autoSelectIfOnlyOne', function (result) { - let options = $parse(result)(scope); + const options = $parse(result)(scope); if (options && options.length === 1) { ngModelCtrl.$setViewValue(options[0]); ngModelCtrl.$render(); diff --git a/src/ui/public/directives/bread_crumbs.js b/src/ui/public/directives/bread_crumbs.js index b5a590a60b308..092ba98c519c0 100644 --- a/src/ui/public/directives/bread_crumbs.js +++ b/src/ui/public/directives/bread_crumbs.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import chrome from 'ui/chrome/chrome'; import breadCrumbsTemplate from 'ui/partials/bread_crumbs.html'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('breadCrumbs', function () { return { diff --git a/src/ui/public/directives/click_focus.js b/src/ui/public/directives/click_focus.js index 5a005676699c8..1c84249a131af 100644 --- a/src/ui/public/directives/click_focus.js +++ b/src/ui/public/directives/click_focus.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('clickFocus', function () { return { @@ -11,7 +11,7 @@ module.directive('clickFocus', function () { restrict: 'A', link: function ($scope, $elem) { function handler() { - let focusElem = $.find('input[name=' + $scope.clickFocus + ']'); + const focusElem = $.find('input[name=' + $scope.clickFocus + ']'); if (focusElem[0]) focusElem[0].focus(); } diff --git a/src/ui/public/directives/confirm_click.js b/src/ui/public/directives/confirm_click.js index 9c83e861ee292..fc7ae54a36499 100644 --- a/src/ui/public/directives/confirm_click.js +++ b/src/ui/public/directives/confirm_click.js @@ -6,9 +6,9 @@ uiModules restrict: 'A', link: function ($scope, $elem, attrs) { $elem.bind('click', function () { - let message = attrs.confirmation || 'Are you sure?'; + const message = attrs.confirmation || 'Are you sure?'; if (window.confirm(message)) { // eslint-disable-line no-alert - let action = attrs.confirmClick; + const action = attrs.confirmClick; if (action) { $scope.$apply($scope.$eval(action)); } diff --git a/src/ui/public/directives/css_truncate.js b/src/ui/public/directives/css_truncate.js index b9541a814d2d2..718ddfdde7080 100644 --- a/src/ui/public/directives/css_truncate.js +++ b/src/ui/public/directives/css_truncate.js @@ -1,7 +1,7 @@ import $ from 'jquery'; import _ from 'lodash'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('cssTruncate', function ($timeout) { return { diff --git a/src/ui/public/directives/field_name.js b/src/ui/public/directives/field_name.js index ffeace0af0f7c..2a1837f610b2e 100644 --- a/src/ui/public/directives/field_name.js +++ b/src/ui/public/directives/field_name.js @@ -1,7 +1,7 @@ import $ from 'jquery'; import 'ui/filters/short_dots'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('fieldName', function ($compile, $rootScope, $filter) { return { @@ -13,7 +13,7 @@ module.directive('fieldName', function ($compile, $rootScope, $filter) { }, link: function ($scope, $el) { - let typeIcon = function (fieldType) { + const typeIcon = function (fieldType) { switch (fieldType) { case 'source': return ''; @@ -45,12 +45,12 @@ module.directive('fieldName', function ($compile, $rootScope, $filter) { 'field.rowCount' ], function () { - let type = $scope.field ? $scope.field.type : $scope.fieldType; - let name = $scope.field ? $scope.field.name : $scope.fieldName; - let results = $scope.field ? !$scope.field.rowCount && !$scope.field.scripted : false; - let scripted = $scope.field ? $scope.field.scripted : false; + const type = $scope.field ? $scope.field.type : $scope.fieldType; + const name = $scope.field ? $scope.field.name : $scope.fieldName; + const results = $scope.field ? !$scope.field.rowCount && !$scope.field.scripted : false; + const scripted = $scope.field ? $scope.field.scripted : false; - let displayName = $filter('shortDots')(name); + const displayName = $filter('shortDots')(name); $el .attr('title', name) diff --git a/src/ui/public/directives/file_upload.js b/src/ui/public/directives/file_upload.js index 06c4752b456bf..80c11403b5759 100644 --- a/src/ui/public/directives/file_upload.js +++ b/src/ui/public/directives/file_upload.js @@ -1,9 +1,9 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); -let html = ''; +const html = ''; module.directive('fileUpload', function () { return { @@ -16,14 +16,14 @@ module.directive('fileUpload', function () { }, template: html, link: function ($scope, $elem, attrs) { - let $button = $elem.find($scope.uploadSelector); - let $dropzone = $elem.find('.dropzone'); + const $button = $elem.find($scope.uploadSelector); + const $dropzone = $elem.find('.dropzone'); const handleFile = (file) => { if (_.isUndefined(file)) return; if (_.has(attrs, 'onRead')) { - let reader = new FileReader(); + const reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { $scope.onRead({fileContents: e.target.result}); @@ -66,7 +66,7 @@ module.directive('fileUpload', function () { $elem.append($fileInput); $fileInput.on('change', function (e) { - let target = e.srcElement || e.target; + const target = e.srcElement || e.target; if (_.get(target, 'files.length')) { handleFile(target.files[0]); } diff --git a/src/ui/public/directives/inequality.js b/src/ui/public/directives/inequality.js index b6e2ed72b0688..44b0d0e977652 100644 --- a/src/ui/public/directives/inequality.js +++ b/src/ui/public/directives/inequality.js @@ -5,8 +5,8 @@ function makeDirectiveDef(id, compare) { return { require: 'ngModel', link: function ($scope, $el, $attr, ngModel) { - let getBound = function () { return $parse($attr[id])(); }; - let defaultVal = { + const getBound = function () { return $parse($attr[id])(); }; + const defaultVal = { 'greaterThan': -Infinity, 'lessThan': Infinity }[id]; @@ -19,8 +19,8 @@ function makeDirectiveDef(id, compare) { }); function validate(val) { - let bound = !isNaN(getBound()) ? +getBound() : defaultVal; - let valid = !isNaN(bound) && !isNaN(val) && compare(val, bound); + const bound = !isNaN(getBound()) ? +getBound() : defaultVal; + const valid = !isNaN(bound) && !isNaN(val) && compare(val, bound); ngModel.$setValidity(id, valid); return val; } diff --git a/src/ui/public/directives/infinite_scroll.js b/src/ui/public/directives/infinite_scroll.js index db1f410f56ed0..4b888cbc60eac 100644 --- a/src/ui/public/directives/infinite_scroll.js +++ b/src/ui/public/directives/infinite_scroll.js @@ -1,6 +1,6 @@ import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('kbnInfiniteScroll', function () { return { @@ -9,20 +9,20 @@ module.directive('kbnInfiniteScroll', function () { more: '=' }, link: function ($scope, $element, attrs) { - let $window = $(window); + const $window = $(window); let checkTimer; function onScroll() { if (!$scope.more) return; - let winHeight = $window.height(); - let winBottom = winHeight + $window.scrollTop(); - let elTop = $element.offset().top; - let remaining = elTop - winBottom; + const winHeight = $window.height(); + const winBottom = winHeight + $window.scrollTop(); + const elTop = $element.offset().top; + const remaining = elTop - winBottom; if (remaining <= winHeight * 0.50) { $scope[$scope.$$phase ? '$eval' : '$apply'](function () { - let more = $scope.more(); + const more = $scope.more(); }); } } diff --git a/src/ui/public/directives/input_datetime.js b/src/ui/public/directives/input_datetime.js index 0559358e83093..3144182932371 100644 --- a/src/ui/public/directives/input_datetime.js +++ b/src/ui/public/directives/input_datetime.js @@ -2,7 +2,7 @@ import $ from 'jquery'; import _ from 'lodash'; import moment from 'moment'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputDatetime', function () { return { @@ -10,18 +10,18 @@ module.directive('inputDatetime', function () { require: 'ngModel', link: function ($scope, $elem, attrs, ngModel) { - let format = 'YYYY-MM-DD HH:mm:ss.SSS'; + const format = 'YYYY-MM-DD HH:mm:ss.SSS'; $elem.after('
' + format + '
'); // What should I make with the input from the user? - let fromUser = function (text) { - let parsed = moment(text, format); + const fromUser = function (text) { + const parsed = moment(text, format); return parsed.isValid() ? parsed : undefined; }; // How should I present the data back to the user in the input field? - let toUser = function (datetime) { + const toUser = function (datetime) { return moment(datetime).format(format); }; diff --git a/src/ui/public/directives/input_focus.js b/src/ui/public/directives/input_focus.js index c6adccfd3e7b0..ce904b459e0f1 100644 --- a/src/ui/public/directives/input_focus.js +++ b/src/ui/public/directives/input_focus.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputFocus', function ($timeout) { return { diff --git a/src/ui/public/directives/input_whole_number.js b/src/ui/public/directives/input_whole_number.js index 5a4f406ea5a9f..adbdd63c08634 100644 --- a/src/ui/public/directives/input_whole_number.js +++ b/src/ui/public/directives/input_whole_number.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputWholeNumber', function () { return { diff --git a/src/ui/public/directives/json_input.js b/src/ui/public/directives/json_input.js index 640b5bd887906..35066233018b8 100644 --- a/src/ui/public/directives/json_input.js +++ b/src/ui/public/directives/json_input.js @@ -15,7 +15,7 @@ uiModules function fromJSON(value) { try { value = JSON.parse(value); - let validity = !scope.$eval(attrs.requireKeys) ? true : _.keys(value).length > 0; + const validity = !scope.$eval(attrs.requireKeys) ? true : _.keys(value).length > 0; ngModelCntrl.$setValidity('json', validity); } catch (e) { ngModelCntrl.$setValidity('json', false); diff --git a/src/ui/public/directives/paginate.js b/src/ui/public/directives/paginate.js index cf11e8ac6fd0d..cd44441ce4fdf 100644 --- a/src/ui/public/directives/paginate.js +++ b/src/ui/public/directives/paginate.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import uiModules from 'ui/modules'; import paginateControlsTemplate from 'ui/partials/paginate_controls.html'; -let PER_PAGE_DEFAULT = 10; +const PER_PAGE_DEFAULT = 10; uiModules.get('kibana') .directive('paginate', function ($parse, $compile) { @@ -22,7 +22,7 @@ uiModules.get('kibana') $el.prepend($compile('')($scope)); } - let paginate = $scope.paginate; + const paginate = $scope.paginate; // add some getters to the controller powered by attributes paginate.getList = $parse(attrs.list); @@ -42,8 +42,8 @@ uiModules.get('kibana') }, controllerAs: 'paginate', controller: function ($scope) { - let self = this; - let ALL = 0; + const self = this; + const ALL = 0; self.sizeOptions = [ { title: '10', value: 10 }, @@ -62,8 +62,8 @@ uiModules.get('kibana') self.perPageProp, self.otherWidthGetter ], function (vals, oldVals) { - let intChanges = vals[0] !== oldVals[0]; - let extChanges = vals[1] !== oldVals[1]; + const intChanges = vals[0] !== oldVals[0]; + const extChanges = vals[1] !== oldVals[1]; if (intChanges) { if (!setPerPage(self.perPage)) { @@ -102,14 +102,14 @@ uiModules.get('kibana') $scope.pages = []; if (!$scope.list) return; - let perPage = _.parseInt(self.perPage); - let count = perPage ? Math.ceil($scope.list.length / perPage) : 1; + const perPage = _.parseInt(self.perPage); + const count = perPage ? Math.ceil($scope.list.length / perPage) : 1; _.times(count, function (i) { let page; if (perPage) { - let start = perPage * i; + const start = perPage * i; page = $scope.list.slice(start, start + perPage); } else { page = $scope.list.slice(0); @@ -144,7 +144,7 @@ uiModules.get('kibana') // setup the list of the other pages to link to $scope.otherPages = []; - let width = +self.otherWidthGetter($scope) || 5; + const width = +self.otherWidthGetter($scope) || 5; let left = page.i - Math.round((width - 1) / 2); let right = left + width - 1; @@ -155,14 +155,14 @@ uiModules.get('kibana') } // shift extra right nums to left - let lastI = page.count - 1; + const lastI = page.count - 1; if (right > lastI) { right = lastI; left = right - width + 1; } for (let i = left; i <= right; i++) { - let other = $scope.pages[i]; + const other = $scope.pages[i]; if (!other) continue; diff --git a/src/ui/public/directives/pretty_duration.js b/src/ui/public/directives/pretty_duration.js index 4354f4d0ebaca..8d9653f80a348 100644 --- a/src/ui/public/directives/pretty_duration.js +++ b/src/ui/public/directives/pretty_duration.js @@ -4,7 +4,7 @@ import moment from 'moment'; import 'ui/timepicker/quick_ranges'; import 'ui/timepicker/time_units'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('prettyDuration', function (config, quickRanges, timeUnits) { @@ -15,9 +15,9 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { to: '=' }, link: function ($scope, $elem) { - let dateFormat = config.get('dateFormat'); + const dateFormat = config.get('dateFormat'); - let lookupByRange = {}; + const lookupByRange = {}; _.each(quickRanges, function (frame) { lookupByRange[frame.from + ' to ' + frame.to] = frame; }); @@ -26,13 +26,13 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { let text; // If both parts are date math, try to look up a reasonable string if ($scope.from && $scope.to && !moment.isMoment($scope.from) && !moment.isMoment($scope.to)) { - let tryLookup = lookupByRange[$scope.from.toString() + ' to ' + $scope.to.toString()]; + const tryLookup = lookupByRange[$scope.from.toString() + ' to ' + $scope.to.toString()]; if (tryLookup) { $elem.text(tryLookup.display); } else { - let fromParts = $scope.from.toString().split('-'); + const fromParts = $scope.from.toString().split('-'); if ($scope.to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) { - let rounded = fromParts[1].split('/'); + const rounded = fromParts[1].split('/'); text = 'Last ' + rounded[0]; if (rounded[1]) { text = text + ' rounded to the ' + timeUnits[rounded[1]]; @@ -49,7 +49,7 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { }; function cantLookup() { - let display = {}; + const display = {}; _.each(['from', 'to'], function (time) { if (moment.isMoment($scope[time])) { display[time] = $scope[time].format(dateFormat); @@ -57,7 +57,7 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { if ($scope[time] === 'now') { display[time] = 'now'; } else { - let tryParse = dateMath.parse($scope[time], time === 'to' ? true : false); + const tryParse = dateMath.parse($scope[time], time === 'to' ? true : false); display[time] = moment.isMoment(tryParse) ? '~ ' + tryParse.fromNow() : $scope[time]; } } diff --git a/src/ui/public/directives/rows.js b/src/ui/public/directives/rows.js index 11f3ae3f2e969..c12ff304b5f7c 100644 --- a/src/ui/public/directives/rows.js +++ b/src/ui/public/directives/rows.js @@ -3,10 +3,10 @@ import _ from 'lodash'; import AggConfigResult from 'ui/vis/agg_config_result'; import FilterBarFilterBarClickHandlerProvider from 'ui/filter_bar/filter_bar_click_handler'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private) { - let filterBarClickHandler = Private(FilterBarFilterBarClickHandlerProvider); + const filterBarClickHandler = Private(FilterBarFilterBarClickHandlerProvider); return { restrict: 'A', link: function ($scope, $el, attr) { @@ -17,10 +17,10 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private // access to it here. This may become a problem with the switch to BigNumber if (_.isNumeric(contents)) $cell.addClass('numeric-value'); - let createAggConfigResultCell = function (aggConfigResult) { - let $cell = $(document.createElement('td')); - let $state = getAppState(); - let clickHandler = filterBarClickHandler($state); + const createAggConfigResultCell = function (aggConfigResult) { + const $cell = $(document.createElement('td')); + const $state = getAppState(); + const clickHandler = filterBarClickHandler($state); $cell.scope = $scope.$new(); $cell.addClass('cell-hover'); $cell.attr('ng-click', 'clickHandler($event)'); @@ -72,18 +72,18 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private attr.kbnRowsMin ], function (vals) { let rows = vals[0]; - let min = vals[1]; + const min = vals[1]; $el.empty(); if (!_.isArray(rows)) rows = []; - let width = rows.reduce(maxRowSize, 0); + const width = rows.reduce(maxRowSize, 0); if (isFinite(min) && rows.length < min) { // clone the rows so that we can add elements to it without upsetting the original rows = _.clone(rows); // crate the empty row which will be pushed into the row list over and over - let emptyRow = new Array(width); + const emptyRow = new Array(width); // fill the empty row with values _.times(width, function (i) { emptyRow[i] = ''; }); // push as many empty rows into the row array as needed @@ -91,7 +91,7 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private } rows.forEach(function (row) { - let $tr = $(document.createElement('tr')).appendTo($el); + const $tr = $(document.createElement('tr')).appendTo($el); row.forEach(function (cell) { addCell($tr, cell); }); diff --git a/src/ui/public/directives/saved_object_finder.js b/src/ui/public/directives/saved_object_finder.js index d936f04342fd9..efa4f7ebf7fcc 100644 --- a/src/ui/public/directives/saved_object_finder.js +++ b/src/ui/public/directives/saved_object_finder.js @@ -4,11 +4,11 @@ import keymap from 'ui/utils/key_map'; import SavedObjectsSavedObjectRegistryProvider from 'ui/saved_objects/saved_object_registry'; import uiModules from 'ui/modules'; import savedObjectFinderTemplate from 'ui/partials/saved_object_finder.html'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Private, config) { - let services = Private(SavedObjectsSavedObjectRegistryProvider).byLoaderPropertiesName; + const services = Private(SavedObjectsSavedObjectRegistryProvider).byLoaderPropertiesName; return { restrict: 'E', @@ -25,16 +25,16 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr template: savedObjectFinderTemplate, controllerAs: 'finder', controller: function ($scope, $element, $timeout) { - let self = this; + const self = this; // the text input element - let $input = $element.find('input[ng-model=filter]'); + const $input = $element.find('input[ng-model=filter]'); // The number of items to show in the list $scope.perPage = config.get('savedObjects:perPage'); // the list that will hold the suggestions - let $list = $element.find('ul'); + const $list = $element.find('ul'); // the current filter string, used to check that returned results are still useful let currentFilter = $scope.filter; @@ -97,7 +97,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr $scope.userOnChoose(hit, $event); } - let url = self.makeUrl(hit); + const url = self.makeUrl(hit); if (!url || url === '#' || url.charAt(0) !== '#') return; $event.preventDefault(); @@ -135,7 +135,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr case 'enter': if (self.hitCount !== 1) return; - let hit = self.hits[0]; + const hit = self.hits[0]; if (!hit) return; self.onChoose(hit, $event); @@ -208,8 +208,8 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr case 'enter': if (!self.selector.enabled) break; - let hitIndex = ((page.number - 1) * paginate.perPage) + self.selector.index; - let hit = self.hits[hitIndex]; + const hitIndex = ((page.number - 1) * paginate.perPage) + self.selector.index; + const hit = self.hits[hitIndex]; if (!hit) break; self.onChoose(hit, $event); @@ -251,7 +251,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr // but ensure that we don't search for the same // thing twice. This is called from multiple places // and needs to be smart about when it actually searches - let filter = currentFilter; + const filter = currentFilter; if (prevSearch === filter) return; prevSearch = filter; @@ -267,7 +267,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr } function scrollIntoView($element, snapTop) { - let el = $element[0]; + const el = $element[0]; if (!el) return; diff --git a/src/ui/public/directives/validate_date_math.js b/src/ui/public/directives/validate_date_math.js index 23c601987e7cd..c433777bd8c1a 100644 --- a/src/ui/public/directives/validate_date_math.js +++ b/src/ui/public/directives/validate_date_math.js @@ -19,7 +19,7 @@ uiModules.get('kibana').directive('validateDateMath', function () { return null; } - let moment = dateMath.parse(input); + const moment = dateMath.parse(input); ngModel.$setValidity('validDateMath', moment != null && moment.isValid()); return input; } diff --git a/src/ui/public/directives/validate_index_name.js b/src/ui/public/directives/validate_index_name.js index 10b51c4dfb8fb..8bc697ad7e575 100644 --- a/src/ui/public/directives/validate_index_name.js +++ b/src/ui/public/directives/validate_index_name.js @@ -15,10 +15,10 @@ uiModules illegalCharacters.push('*'); } - let isValid = function (input) { + const isValid = function (input) { if (input == null || input === '' || input === '.' || input === '..') return false; - let match = _.find(illegalCharacters, function (character) { + const match = _.find(illegalCharacters, function (character) { return input.indexOf(character) >= 0; }); return !match; diff --git a/src/ui/public/directives/validate_json.js b/src/ui/public/directives/validate_json.js index bf4df84f69da8..82253adb9159c 100644 --- a/src/ui/public/directives/validate_json.js +++ b/src/ui/public/directives/validate_json.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('validateJson', function ($compile) { return { diff --git a/src/ui/public/doc_table/__tests__/doc_table.js b/src/ui/public/doc_table/__tests__/doc_table.js index b5dc9c3dcbbf6..0bd7cf203e28d 100644 --- a/src/ui/public/doc_table/__tests__/doc_table.js +++ b/src/ui/public/doc_table/__tests__/doc_table.js @@ -23,7 +23,7 @@ let $timeout; let searchSource; -let init = function ($elem, props) { +const init = function ($elem, props) { ngMock.inject(function ($rootScope, $compile, _$timeout_) { $timeout = _$timeout_; $parentScope = $rootScope; @@ -41,7 +41,7 @@ let init = function ($elem, props) { }); }; -let destroy = function () { +const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; diff --git a/src/ui/public/doc_table/__tests__/lib/get_sort.js b/src/ui/public/doc_table/__tests__/lib/get_sort.js index 3fc141bad8336..6a0aed4b8ba08 100644 --- a/src/ui/public/doc_table/__tests__/lib/get_sort.js +++ b/src/ui/public/doc_table/__tests__/lib/get_sort.js @@ -1,5 +1,5 @@ import getSort from 'ui/doc_table/lib/get_sort'; -let defaultSort = {time: 'desc'}; +const defaultSort = {time: 'desc'}; import expect from 'expect.js'; import ngMock from 'ng_mock'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; diff --git a/src/ui/public/doc_table/__tests__/lib/rows_headers.js b/src/ui/public/doc_table/__tests__/lib/rows_headers.js index f68527482c15e..36e9b786741b9 100644 --- a/src/ui/public/doc_table/__tests__/lib/rows_headers.js +++ b/src/ui/public/doc_table/__tests__/lib/rows_headers.js @@ -28,7 +28,7 @@ describe('Doc Table', function () { })); // Sets up the directive, take an element, and a list of properties to attach to the parent scope. - let init = function ($elem, props) { + const init = function ($elem, props) { ngMock.inject(function ($compile) { _.assign($parentScope, props); $compile($elem)($parentScope); @@ -37,17 +37,17 @@ describe('Doc Table', function () { }); }; - let destroy = function () { + const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; // For testing column removing/adding for the header and the rows // - let columnTests = function (elemType, parentElem) { + const columnTests = function (elemType, parentElem) { it('should create a time column if the timefield is defined', function (done) { - let childElems = parentElem.find(elemType); + const childElems = parentElem.find(elemType); expect(childElems.length).to.be(2); done(); }); @@ -79,7 +79,7 @@ describe('Doc Table', function () { delete parentElem.scope().indexPattern.timeFieldName; parentElem.scope().$digest(); - let childElems = parentElem.find(elemType); + const childElems = parentElem.find(elemType); expect(childElems.length).to.be(1); done(); }); @@ -89,7 +89,7 @@ describe('Doc Table', function () { describe('kbnTableHeader', function () { - let $elem = angular.element( + const $elem = angular.element( '' ); @@ -120,7 +120,7 @@ describe('Doc Table', function () { }); it('should sort asc by default, then by desc if already sorting', function (done) { - let fields = ['bytes', '@timestamp']; + const fields = ['bytes', '@timestamp']; // Should not be sorted at first expect($scope.sorting).to.eql(undefined); @@ -201,7 +201,7 @@ describe('Doc Table', function () { }); describe('kbnTableRow', function () { - let $elem = angular.element( + const $elem = angular.element( ''); $el.empty(); - let init = function () { + const init = function () { createSummaryRow($scope.row, $scope.row._id); }; @@ -53,7 +53,7 @@ module.directive('kbnTableRow', function ($compile) { // toggle display of the rows details, a full list of the fields from each row $scope.toggleRow = function () { - let $detailsTr = $el.next(); + const $detailsTr = $el.next(); $scope.open = !$scope.open; @@ -90,10 +90,10 @@ module.directive('kbnTableRow', function ($compile) { // create a tr element that lists the value for each *column* function createSummaryRow(row) { - let indexPattern = $scope.indexPattern; + const indexPattern = $scope.indexPattern; // We just create a string here because its faster. - let newHtmls = [ + const newHtmls = [ openRowHtml ]; @@ -114,16 +114,16 @@ module.directive('kbnTableRow', function ($compile) { let $cells = $el.children(); newHtmls.forEach(function (html, i) { - let $cell = $cells.eq(i); + const $cell = $cells.eq(i); if ($cell.data('discover:html') === html) return; - let reuse = _.find($cells.slice(i + 1), function (cell) { + const reuse = _.find($cells.slice(i + 1), function (cell) { return $.data(cell, 'discover:html') === html; }); - let $target = reuse ? $(reuse).detach() : $(html); + const $target = reuse ? $(reuse).detach() : $(html); $target.data('discover:html', html); - let $before = $cells.eq(i - 1); + const $before = $cells.eq(i - 1); if ($before.size()) { $before.after($target); } else { @@ -151,7 +151,7 @@ module.directive('kbnTableRow', function ($compile) { * Fill an element with the value of a field */ function _displayField(row, fieldName, breakWords) { - let indexPattern = $scope.indexPattern; + const indexPattern = $scope.indexPattern; let text = indexPattern.formatField(row, fieldName); if (breakWords) { diff --git a/src/ui/public/doc_table/doc_table.js b/src/ui/public/doc_table/doc_table.js index db3148a831525..c54e78f54724c 100644 --- a/src/ui/public/doc_table/doc_table.js +++ b/src/ui/public/doc_table/doc_table.js @@ -25,15 +25,15 @@ uiModules.get('kibana') filter: '=?', }, link: function ($scope) { - let notify = new Notifier(); + const notify = new Notifier(); $scope.limit = 50; $scope.persist = { sorting: $scope.sorting, columns: $scope.columns }; - let prereq = (function () { - let fns = []; + const prereq = (function () { + const fns = []; return function register(fn) { fns.push(fn); @@ -59,7 +59,7 @@ uiModules.get('kibana') $scope.$watch('columns', function (columns) { if (columns.length !== 0) return; - let $state = getAppState(); + const $state = getAppState(); $scope.columns.push('_source'); if ($state) $state.replace(); }); diff --git a/src/ui/public/doc_table/lib/get_sort.js b/src/ui/public/doc_table/lib/get_sort.js index e9f99615b1fce..c0124132083c7 100644 --- a/src/ui/public/doc_table/lib/get_sort.js +++ b/src/ui/public/doc_table/lib/get_sort.js @@ -7,7 +7,7 @@ import _ from 'lodash'; * @returns {object} a sort object suitable for returning to elasticsearch */ function getSort(sort, indexPattern) { - let sortObj = {}; + const sortObj = {}; let field; let direction; diff --git a/src/ui/public/doc_title/__tests__/doc_title.js b/src/ui/public/doc_title/__tests__/doc_title.js index faf38f9521473..104b3032dcadf 100644 --- a/src/ui/public/doc_title/__tests__/doc_title.js +++ b/src/ui/public/doc_title/__tests__/doc_title.js @@ -6,7 +6,7 @@ import DocTitleProvider from 'ui/doc_title'; describe('docTitle Service', function () { let initialDocTitle; - let MAIN_TITLE = 'Kibana 4'; + const MAIN_TITLE = 'Kibana 4'; let docTitle; let $rootScope; @@ -36,9 +36,9 @@ describe('docTitle Service', function () { describe('setup', function () { it('resets the title when a route change begins', function () { - let spy = $rootScope.$on; + const spy = $rootScope.$on; - let found = spy.args.some(function (args) { + const found = spy.args.some(function (args) { return args[0] === '$routeChangeStart' && args[1] === docTitle.reset; }); diff --git a/src/ui/public/doc_title/doc_title.js b/src/ui/public/doc_title/doc_title.js index 6f58e162ae5e5..32a1b4744d8d8 100644 --- a/src/ui/public/doc_title/doc_title.js +++ b/src/ui/public/doc_title/doc_title.js @@ -10,15 +10,15 @@ uiModules.get('kibana') $rootScope.$on('$routeChangeSuccess', docTitle.update); }) .service('docTitle', function ($rootScope) { - let baseTitle = document.title; - let self = this; + const baseTitle = document.title; + const self = this; let lastChange; function render() { lastChange = lastChange || []; - let parts = [lastChange[0]]; + const parts = [lastChange[0]]; if (!lastChange[1]) parts.push(baseTitle); diff --git a/src/ui/public/factories/__tests__/base_object.js b/src/ui/public/factories/__tests__/base_object.js index 758ba090d679c..de7815130962e 100644 --- a/src/ui/public/factories/__tests__/base_object.js +++ b/src/ui/public/factories/__tests__/base_object.js @@ -16,31 +16,31 @@ describe('Base Object', function () { })); it('should take an inital set of values', function () { - let baseObject = new BaseObject({ message: 'test' }); + const baseObject = new BaseObject({ message: 'test' }); expect(baseObject).to.have.property('message', 'test'); }); it('should serialize _attributes to RISON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.message = 'Testing... 1234'; - let rison = baseObject.toRISON(); + const rison = baseObject.toRISON(); expect(rison).to.equal('(message:\'Testing... 1234\')'); }); it('should not serialize $$attributes to RISON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.$$attributes = { foo: 'bar' }; baseObject.message = 'Testing... 1234'; - let rison = baseObject.toRISON(); + const rison = baseObject.toRISON(); expect(rison).to.equal('(message:\'Testing... 1234\')'); }); it('should serialize _attributes for JSON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.message = 'Testing... 1234'; baseObject._private = 'foo'; baseObject.$private = 'stuff'; - let json = JSON.stringify(baseObject); + const json = JSON.stringify(baseObject); expect(json).to.equal('{"message":"Testing... 1234"}'); }); diff --git a/src/ui/public/factories/__tests__/events.js b/src/ui/public/factories/__tests__/events.js index 659490bbbb126..974f07b922148 100644 --- a/src/ui/public/factories/__tests__/events.js +++ b/src/ui/public/factories/__tests__/events.js @@ -24,8 +24,8 @@ describe('Events', function () { })); it('should handle on events', function () { - let obj = new Events(); - let prom = obj.on('test', function (message) { + const obj = new Events(); + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -39,9 +39,9 @@ describe('Events', function () { function MyEventedObject() { MyEventedObject.Super.call(this); } - let obj = new MyEventedObject(); + const obj = new MyEventedObject(); - let prom = obj.on('test', function (message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -51,7 +51,7 @@ describe('Events', function () { }); it('should clear events when off is called', function () { - let obj = new Events(); + const obj = new Events(); obj.on('test', _.noop); expect(obj._listeners).to.have.property('test'); expect(obj._listeners.test).to.have.length(1); @@ -60,9 +60,9 @@ describe('Events', function () { }); it('should clear a specific handler when off is called for an event', function () { - let obj = new Events(); - let handler1 = sinon.stub(); - let handler2 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); + const handler2 = sinon.stub(); obj.on('test', handler1); obj.on('test', handler2); expect(obj._listeners).to.have.property('test'); @@ -76,8 +76,8 @@ describe('Events', function () { }); it('should clear a all handlers when off is called for an event', function () { - let obj = new Events(); - let handler1 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); obj.on('test', handler1); expect(obj._listeners).to.have.property('test'); obj.off('test'); @@ -90,11 +90,11 @@ describe('Events', function () { }); it('should handle mulitple identical emits in the same tick', function () { - let obj = new Events(); - let handler1 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); obj.on('test', handler1); - let emits = [ + const emits = [ obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three') @@ -111,9 +111,9 @@ describe('Events', function () { }); it('should handle emits from the handler', function () { - let obj = new Events(); - let secondEmit = Promise.defer(); - let handler1 = sinon.spy(function () { + const obj = new Events(); + const secondEmit = Promise.defer(); + const handler1 = sinon.spy(function () { if (handler1.calledTwice) { return; } @@ -133,12 +133,12 @@ describe('Events', function () { }); it('should only emit to handlers registered before emit is called', function () { - let obj = new Events(); - let handler1 = sinon.stub(); - let handler2 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); + const handler2 = sinon.stub(); obj.on('test', handler1); - let emits = [ + const emits = [ obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three') @@ -150,7 +150,7 @@ describe('Events', function () { obj.on('test', handler2); - let emits2 = [ + const emits2 = [ obj.emit('test', 'four'), obj.emit('test', 'five'), obj.emit('test', 'six') @@ -165,9 +165,9 @@ describe('Events', function () { }); it('should pass multiple arguments from the emitter', function () { - let obj = new Events(); - let handler = sinon.stub(); - let payload = [ + const obj = new Events(); + const handler = sinon.stub(); + const payload = [ 'one', { hello: 'tests' }, null @@ -183,8 +183,8 @@ describe('Events', function () { }); it('should preserve the scope of the handler', function () { - let obj = new Events(); - let expected = 'some value'; + const obj = new Events(); + const expected = 'some value'; let testValue; function handler(arg1, arg2) { @@ -200,9 +200,9 @@ describe('Events', function () { }); it('should always emit in the same order', function () { - let handler = sinon.stub(); + const handler = sinon.stub(); - let obj = new Events(); + const obj = new Events(); obj.on('block', _.partial(handler, 'block')); obj.on('last', _.partial(handler, 'last')); diff --git a/src/ui/public/fancy_forms/fancy_forms.js b/src/ui/public/fancy_forms/fancy_forms.js index 457b1aa01442d..c96e520505678 100644 --- a/src/ui/public/fancy_forms/fancy_forms.js +++ b/src/ui/public/fancy_forms/fancy_forms.js @@ -12,16 +12,16 @@ uiModules // directive providers are arrays $delegate.forEach(function (directive) { // get metadata about all init fns - let chain = [directive.controller, DecorativeController].map(function (fn) { - let deps = $injector.annotate(fn); + const chain = [directive.controller, DecorativeController].map(function (fn) { + const deps = $injector.annotate(fn); return { deps: deps, fn: _.isArray(fn) ? _.last(fn) : fn }; }); // replace the controller with one that will setup the actual controller directive.controller = function stub() { - let allDeps = _.toArray(arguments); + const allDeps = _.toArray(arguments); return chain.reduce(function (controller, link, i) { - let deps = allDeps.splice(0, link.deps.length); + const deps = allDeps.splice(0, link.deps.length); return link.fn.apply(controller, deps) || controller; }, this); }; diff --git a/src/ui/public/fancy_forms/kbn_form_controller.js b/src/ui/public/fancy_forms/kbn_form_controller.js index c4b9f4ef19717..ccb93885a349f 100644 --- a/src/ui/public/fancy_forms/kbn_form_controller.js +++ b/src/ui/public/fancy_forms/kbn_form_controller.js @@ -7,7 +7,7 @@ import _ from 'lodash'; * @param {$scope} $scope */ function KbnFormController($scope, $element) { - let self = this; + const self = this; self.errorCount = function (predicate) { return self.$$invalidModels().length; @@ -21,14 +21,14 @@ function KbnFormController($scope, $element) { }; self.describeErrors = function () { - let count = self.softErrorCount(); + const count = self.softErrorCount(); return count + ' Error' + (count === 1 ? '' : 's'); }; self.$$invalidModels = function (predicate) { predicate = _.callback(predicate); - let invalid = []; + const invalid = []; _.forOwn(self.$error, function collect(models) { if (!models) return; diff --git a/src/ui/public/field_editor/__tests__/field_editor.js b/src/ui/public/field_editor/__tests__/field_editor.js index 43b200fde76ca..528095b175b90 100644 --- a/src/ui/public/field_editor/__tests__/field_editor.js +++ b/src/ui/public/field_editor/__tests__/field_editor.js @@ -41,7 +41,7 @@ describe('FieldEditor directive', function () { it('exposes $scope.editor, a controller for the editor', function () { compile(); - let editor = $scope.editor; + const editor = $scope.editor; expect(editor).to.be.an('object'); }); }); @@ -81,8 +81,8 @@ describe('FieldEditor directive', function () { }); it('reflects changes to the index patterns field', function () { - let a = {}; - let b = {}; + const a = {}; + const b = {}; actual.script = a; expect(field.script).to.be(a); @@ -92,7 +92,7 @@ describe('FieldEditor directive', function () { }); it('is fully mutable, unlike the index patterns field', function () { - let origName = actual.name; + const origName = actual.name; actual.name = 'john'; expect(actual.name).to.not.be('john'); expect(actual.name).to.be(origName); diff --git a/src/ui/public/field_editor/field_editor.js b/src/ui/public/field_editor/field_editor.js index 57f9006dfa831..b7772485e0ff5 100644 --- a/src/ui/public/field_editor/field_editor.js +++ b/src/ui/public/field_editor/field_editor.js @@ -11,10 +11,10 @@ import fieldEditorTemplate from 'ui/field_editor/field_editor.html'; uiModules .get('kibana', ['colorpicker.module']) .directive('fieldEditor', function (Private, $sce) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let Field = Private(IndexPatternsFieldProvider); - let scriptingInfo = $sce.trustAsHtml(require('ui/field_editor/scripting_info.html')); - let scriptingWarning = $sce.trustAsHtml(require('ui/field_editor/scripting_warning.html')); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const Field = Private(IndexPatternsFieldProvider); + const scriptingInfo = $sce.trustAsHtml(require('ui/field_editor/scripting_info.html')); + const scriptingWarning = $sce.trustAsHtml(require('ui/field_editor/scripting_warning.html')); return { restrict: 'E', @@ -25,8 +25,8 @@ uiModules }, controllerAs: 'editor', controller: function ($scope, Notifier, kbnUrl) { - let self = this; - let notify = new Notifier({ location: 'Field Editor' }); + const self = this; + const notify = new Notifier({ location: 'Field Editor' }); self.scriptingInfo = scriptingInfo; self.scriptingWarning = scriptingWarning; @@ -43,9 +43,9 @@ uiModules self.cancel = redirectAway; self.save = function () { - let indexPattern = self.indexPattern; - let fields = indexPattern.fields; - let field = self.field.toActualField(); + const indexPattern = self.indexPattern; + const fields = indexPattern.fields; + const field = self.field.toActualField(); fields.remove({ name: field.name }); fields.push(field); @@ -64,8 +64,8 @@ uiModules }; self.delete = function () { - let indexPattern = self.indexPattern; - let field = self.field; + const indexPattern = self.indexPattern; + const field = self.field; indexPattern.fields.remove({ name: field.name }); return indexPattern.save() @@ -76,9 +76,9 @@ uiModules }; $scope.$watch('editor.selectedFormatId', function (cur, prev) { - let format = self.field.format; - let changedFormat = cur !== prev; - let missingFormat = cur && (!format || format.type.id !== cur); + const format = self.field.format; + const changedFormat = cur !== prev; + const missingFormat = cur && (!format || format.type.id !== cur); if (!changedFormat || !missingFormat) return; @@ -87,15 +87,15 @@ uiModules }); $scope.$watch('editor.formatParams', function () { - let FieldFormat = getFieldFormatType(); + const FieldFormat = getFieldFormatType(); self.field.format = new FieldFormat(self.formatParams); }, true); // copy the defined properties of the field to a plain object // which is mutable, and capture the changed seperately. function shadowCopy(field) { - let changes = {}; - let shadowProps = { + const changes = {}; + const shadowProps = { toActualField: { // bring the shadow copy out of the shadows value: function toActualField() { @@ -105,7 +105,7 @@ uiModules }; Object.getOwnPropertyNames(field).forEach(function (prop) { - let desc = Object.getOwnPropertyDescriptor(field, prop); + const desc = Object.getOwnPropertyDescriptor(field, prop); shadowProps[prop] = { enumerable: desc.enumerable, get: function () { @@ -130,7 +130,7 @@ uiModules } function initDefaultFormat() { - let def = Object.create(fieldFormats.getDefaultType(self.field.type)); + const def = Object.create(fieldFormats.getDefaultType(self.field.type)); // explicitly set to undefined to prevent inheritting the prototypes id def.id = undefined; diff --git a/src/ui/public/field_format_editor/field_format_editor.js b/src/ui/public/field_format_editor/field_format_editor.js index 962e1668397b0..85092ba9c6fe3 100644 --- a/src/ui/public/field_format_editor/field_format_editor.js +++ b/src/ui/public/field_format_editor/field_format_editor.js @@ -13,7 +13,7 @@ uiModules }, controllerAs: 'editor', controller: function ($scope) { - let self = this; + const self = this; // bind the scope values to the controller, down with $scope.values $scope.editor = this; @@ -40,7 +40,7 @@ uiModules * @return {undefined} */ $scope.$watch('editor.field.format.type', function (FieldFormat) { - let opts = FieldFormat && FieldFormat.editor; + const opts = FieldFormat && FieldFormat.editor; if (!opts) { delete self.$$pseudoDirective; @@ -67,14 +67,14 @@ uiModules }, link: function ($scope, $el) { - let scopesToTeardown = []; + const scopesToTeardown = []; function setupScope(opts) { if (typeof opts !== 'object') { return scopesToTeardown[scopesToTeardown.push($scope.$new()) - 1]; } - let isolate = scopesToTeardown[scopesToTeardown.push($scope.$new(true)) - 1]; + const isolate = scopesToTeardown[scopesToTeardown.push($scope.$new(true)) - 1]; _.forOwn(opts, function (from, to) { isolate.$bind(to, from, $scope); }); @@ -88,20 +88,20 @@ uiModules if (!directive) return $el.hide(); else $el.show(); - let askedForChild = !!directive.scope; - let reuseScope = !askedForChild && !directive.controller; + const askedForChild = !!directive.scope; + const reuseScope = !askedForChild && !directive.controller; - let $formatEditor = $('
').html(directive.template); - let $formatEditorScope = reuseScope ? $scope : setupScope(directive.scope); + const $formatEditor = $('
').html(directive.template); + const $formatEditorScope = reuseScope ? $scope : setupScope(directive.scope); if (directive.controller) { // bind the controller to the injected element - let cntrlAs = (directive.controllerAs ? ' as ' + directive.controllerAs : ''); + const cntrlAs = (directive.controllerAs ? ' as ' + directive.controllerAs : ''); $formatEditorScope.Controller = directive.controller; $formatEditor.attr('ng-controller', 'Controller' + cntrlAs); } - let attrs = {}; + const attrs = {}; let linkFns = directive.compile && directive.compile($el, attrs); if (!linkFns || _.isFunction(linkFns)) { linkFns = { diff --git a/src/ui/public/field_format_editor/pattern/pattern.js b/src/ui/public/field_format_editor/pattern/pattern.js index b13610f8c84f6..5e493c9a6807c 100644 --- a/src/ui/public/field_format_editor/pattern/pattern.js +++ b/src/ui/public/field_format_editor/pattern/pattern.js @@ -11,7 +11,7 @@ uiModules require: ['ngModel', '^fieldEditor'], scope: true, link: function ($scope, $el, attrs, cntrls) { - let ngModelCntrl = cntrls[0]; + const ngModelCntrl = cntrls[0]; $scope.$bind('inputs', attrs.inputs); $scope.$bind('placeholder', attrs.placeholder); diff --git a/src/ui/public/field_format_editor/samples/samples.js b/src/ui/public/field_format_editor/samples/samples.js index d391af37d1556..a0090bbc0e060 100644 --- a/src/ui/public/field_format_editor/samples/samples.js +++ b/src/ui/public/field_format_editor/samples/samples.js @@ -11,7 +11,7 @@ uiModules require: ['?^ngModel', '^fieldEditor'], scope: true, link: function ($scope, $el, attrs, cntrls) { - let ngModelCntrl = cntrls[0]; + const ngModelCntrl = cntrls[0]; $scope.samples = null; $scope.$bind('inputs', attrs.inputs); @@ -21,14 +21,14 @@ uiModules '[]inputs' ], function () { $scope.samples = null; - let field = $scope.editor.field; + const field = $scope.editor.field; if (!field || !field.format) { return; } Promise.try(function () { - let converter = field.format.getConverterFor('html'); + const converter = field.format.getConverterFor('html'); $scope.samples = _.map($scope.inputs, function (input) { return [input, $sce.trustAsHtml(converter(input))]; }); diff --git a/src/ui/public/filter_bar/__tests__/_add_filters.js b/src/ui/public/filter_bar/__tests__/_add_filters.js index 8265d7f2705c4..5c280ce62818d 100644 --- a/src/ui/public/filter_bar/__tests__/_add_filters.js +++ b/src/ui/public/filter_bar/__tests__/_add_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('add filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -88,7 +88,7 @@ describe('add filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); // set up the watchers, add new filters, and crank the digest loop $rootScope.$digest(); @@ -109,7 +109,7 @@ describe('add filters', function () { describe('filter reconciliation', function () { it('should de-dupe appState filters being added', function () { - let newFilter = _.cloneDeep(filters[1]); + const newFilter = _.cloneDeep(filters[1]); appState.filters = filters; $rootScope.$digest(); expect(appState.filters.length).to.be(3); @@ -120,7 +120,7 @@ describe('add filters', function () { }); it('should de-dupe globalState filters being added', function () { - let newFilter = _.cloneDeep(filters[1]); + const newFilter = _.cloneDeep(filters[1]); globalState.filters = filters; $rootScope.$digest(); expect(globalState.filters.length).to.be(3); @@ -131,16 +131,16 @@ describe('add filters', function () { }); it('should mutate global filters on appState filter changes', function () { - let idx = 1; + const idx = 1; globalState.filters = filters; $rootScope.$digest(); - let appFilter = _.cloneDeep(filters[idx]); + const appFilter = _.cloneDeep(filters[idx]); appFilter.meta.negate = true; queryFilter.addFilters(appFilter); $rootScope.$digest(); - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(3); _.each(res, function (filter, i) { expect(filter.$state.store).to.be('globalState'); diff --git a/src/ui/public/filter_bar/__tests__/_get_filters.js b/src/ui/public/filter_bar/__tests__/_get_filters.js index 6c1e3ee4b140a..d7df4834988ed 100644 --- a/src/ui/public/filter_bar/__tests__/_get_filters.js +++ b/src/ui/public/filter_bar/__tests__/_get_filters.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('get filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -55,7 +55,7 @@ describe('get filters', function () { expect(res[1]).to.eql(filters[0]); // should return updated version of filters - let newFilter = { query: { match: { '_type': { query: 'nginx', type: 'phrase' } } } }; + const newFilter = { query: { match: { '_type': { query: 'nginx', type: 'phrase' } } } }; appState.filters.push(newFilter); res = queryFilter.getFilters(); @@ -66,13 +66,13 @@ describe('get filters', function () { appState.filters = [filters[0]]; globalState.filters = [filters[1]]; - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res[0].$state.store).to.be(storeNames.global); expect(res[1].$state.store).to.be(storeNames.app); }); it('should return non-null filters from specific states', function () { - let states = [ + const states = [ [ globalState, queryFilter.getGlobalFilters ], [ appState, queryFilter.getAppFilters ], ]; @@ -81,14 +81,14 @@ describe('get filters', function () { state[0].filters = filters.slice(0); expect(state[0].filters).to.contain(null); - let res = state[1](); + const res = state[1](); expect(res.length).to.be(state[0].filters.length); expect(state[0].filters).to.not.contain(null); }); }); it('should replace the state, not save it', function () { - let states = [ + const states = [ [ globalState, queryFilter.getGlobalFilters ], [ appState, queryFilter.getAppFilters ], ]; @@ -102,7 +102,7 @@ describe('get filters', function () { expect(state[0].replace.called).to.be(false); state[0].filters = filters.slice(0); - let res = state[1](); + const res = state[1](); expect(state[0].save.called).to.be(false); expect(state[0].replace.called).to.be(true); }); @@ -131,11 +131,11 @@ describe('get filters', function () { it('should skip appState filters that match globalState filters', function () { globalState.filters = filters; - let appFilter = _.cloneDeep(filters[1]); + const appFilter = _.cloneDeep(filters[1]); appState.filters.push(appFilter); // global filters should be listed first - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(3); _.each(res, function (filter) { expect(filter.$state.store).to.be('globalState'); @@ -144,12 +144,12 @@ describe('get filters', function () { it('should append conflicting appState filters', function () { globalState.filters = filters; - let appFilter = _.cloneDeep(filters[1]); + const appFilter = _.cloneDeep(filters[1]); appFilter.meta.negate = true; appState.filters.push(appFilter); // global filters should be listed first - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(4); expect(res.filter(function (filter) { return filter.$state.store === storeNames.global; @@ -162,7 +162,7 @@ describe('get filters', function () { it('should not affect disabled filters', function () { // test adding to globalState globalState.filters = _.map(filters, function (filter) { - let f = _.cloneDeep(filter); + const f = _.cloneDeep(filter); f.meta.disabled = true; return f; }); @@ -172,7 +172,7 @@ describe('get filters', function () { // test adding to appState globalState.filters = _.map(filters, function (filter) { - let f = _.cloneDeep(filter); + const f = _.cloneDeep(filter); f.meta.disabled = true; return f; }); diff --git a/src/ui/public/filter_bar/__tests__/_invert_filters.js b/src/ui/public/filter_bar/__tests__/_invert_filters.js index 4148268eb4370..55760e869b1cf 100644 --- a/src/ui/public/filter_bar/__tests__/_invert_filters.js +++ b/src/ui/public/filter_bar/__tests__/_invert_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('invert filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -76,7 +76,7 @@ describe('invert filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; // set up the watchers diff --git a/src/ui/public/filter_bar/__tests__/_pin_filters.js b/src/ui/public/filter_bar/__tests__/_pin_filters.js index 4f11d7dadcd20..c5c9da43800e5 100644 --- a/src/ui/public/filter_bar/__tests__/_pin_filters.js +++ b/src/ui/public/filter_bar/__tests__/_pin_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('pin filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -87,7 +87,7 @@ describe('pin filters', function () { }); it('should move filter from appState to globalState', function () { - let filter = appState.filters[1]; + const filter = appState.filters[1]; queryFilter.pinFilter(filter); expect(globalState.filters).to.contain(filter); @@ -96,7 +96,7 @@ describe('pin filters', function () { }); it('should move filter from globalState to appState', function () { - let filter = globalState.filters[1]; + const filter = globalState.filters[1]; queryFilter.pinFilter(filter); expect(appState.filters).to.contain(filter); @@ -106,8 +106,8 @@ describe('pin filters', function () { it('should only fire the update event', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); - let filter = appState.filters[1]; + const emitSpy = sinon.spy(queryFilter, 'emit'); + const filter = appState.filters[1]; $rootScope.$digest(); queryFilter.pinFilter(filter); @@ -131,8 +131,8 @@ describe('pin filters', function () { }); it('should swap the filters in both states', function () { - let appSample = _.sample(appState.filters); - let globalSample = _.sample(globalState.filters); + const appSample = _.sample(appState.filters); + const globalSample = _.sample(globalState.filters); queryFilter.pinAll(); expect(globalState.filters).to.have.length(5); diff --git a/src/ui/public/filter_bar/__tests__/_remove_filters.js b/src/ui/public/filter_bar/__tests__/_remove_filters.js index 1020536be3692..718aa30c11393 100644 --- a/src/ui/public/filter_bar/__tests__/_remove_filters.js +++ b/src/ui/public/filter_bar/__tests__/_remove_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('remove filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -69,7 +69,7 @@ describe('remove filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; $rootScope.$digest(); @@ -116,7 +116,7 @@ describe('remove filters', function () { appState.filters.push(filters[2]); $rootScope.$digest(); - let missedFilter = _.cloneDeep(filters[0]); + const missedFilter = _.cloneDeep(filters[0]); missedFilter.meta = { negate: !filters[0].meta.negate }; diff --git a/src/ui/public/filter_bar/__tests__/_toggle_filters.js b/src/ui/public/filter_bar/__tests__/_toggle_filters.js index 4a7f4870654c2..9545c184ba79b 100644 --- a/src/ui/public/filter_bar/__tests__/_toggle_filters.js +++ b/src/ui/public/filter_bar/__tests__/_toggle_filters.js @@ -5,7 +5,7 @@ import sinon from 'auto-release-sinon'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('toggle filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -75,7 +75,7 @@ describe('toggle filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; $rootScope.$digest(); diff --git a/src/ui/public/filter_bar/__tests__/_update_filters.js b/src/ui/public/filter_bar/__tests__/_update_filters.js index efc813e2fff83..176f7543730db 100644 --- a/src/ui/public/filter_bar/__tests__/_update_filters.js +++ b/src/ui/public/filter_bar/__tests__/_update_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('update filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; diff --git a/src/ui/public/filter_bar/__tests__/filter_bar.js b/src/ui/public/filter_bar/__tests__/filter_bar.js index 1228943506c6b..807765884ef22 100644 --- a/src/ui/public/filter_bar/__tests__/filter_bar.js +++ b/src/ui/public/filter_bar/__tests__/filter_bar.js @@ -43,7 +43,7 @@ describe('Filter Bar Directive', function () { Promise = $injector.get('Promise'); mapFilter = Private(FilterBarLibMapFilterProvider); - let queryFilter = Private(FilterBarQueryFilterProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); queryFilter.getFilters = function () { return appState.filters; }; @@ -52,7 +52,7 @@ describe('Filter Bar Directive', function () { describe('Element rendering', function () { beforeEach(function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }, { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'nginx' } } } }, { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }, @@ -66,7 +66,7 @@ describe('Filter Bar Directive', function () { $scope = $el.isolateScope(); }); - let off = $rootScope.$on('filterbar:updated', function () { + const off = $rootScope.$on('filterbar:updated', function () { off(); // force a nextTick so it continues *after* the $digest loop completes setTimeout(done, 0); @@ -77,7 +77,7 @@ describe('Filter Bar Directive', function () { }); it('should render all the filters in state', function () { - let filters = $el.find('.filter'); + const filters = $el.find('.filter'); expect(filters).to.have.length(5); expect($(filters[0]).find('span')[0].innerHTML).to.equal('_type:'); expect($(filters[0]).find('span')[1].innerHTML).to.equal('"apache"'); @@ -90,7 +90,7 @@ describe('Filter Bar Directive', function () { }); it('should be able to set an alias', function () { - let filter = $el.find('.filter')[4]; + const filter = $el.find('.filter')[4]; expect($(filter).find('span')[0].innerHTML).to.equal('foo'); }); diff --git a/src/ui/public/filter_bar/__tests__/push_filter.js b/src/ui/public/filter_bar/__tests__/push_filter.js index a38011f79b3c4..d166479a1c1dd 100644 --- a/src/ui/public/filter_bar/__tests__/push_filter.js +++ b/src/ui/public/filter_bar/__tests__/push_filter.js @@ -32,7 +32,7 @@ describe('Filter Bar pushFilter()', function () { })); it('should create the filters property it needed', function () { - let altState = {}; + const altState = {}; pushFilterFn(altState)(filter); expect(altState.filters).to.be.an(Array); }); diff --git a/src/ui/public/filter_bar/filter_bar.js b/src/ui/public/filter_bar/filter_bar.js index d16b64332c0e9..068f7b92f3afe 100644 --- a/src/ui/public/filter_bar/filter_bar.js +++ b/src/ui/public/filter_bar/filter_bar.js @@ -11,17 +11,17 @@ import FilterBarLibFilterOutTimeBasedFilterProvider from 'ui/filter_bar/lib/filt import FilterBarLibChangeTimeFilterProvider from 'ui/filter_bar/lib/change_time_filter'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('filterBar', function (Private, Promise, getAppState) { - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); - let mapFlattenAndWrapFilters = Private(FilterBarLibMapFlattenAndWrapFiltersProvider); - let extractTimeFilter = Private(FilterBarLibExtractTimeFilterProvider); - let filterOutTimeBasedFilter = Private(FilterBarLibFilterOutTimeBasedFilterProvider); - let changeTimeFilter = Private(FilterBarLibChangeTimeFilterProvider); - let queryFilter = Private(FilterBarQueryFilterProvider); - let privateFilterFieldRegex = /(^\$|meta)/; + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const mapFlattenAndWrapFilters = Private(FilterBarLibMapFlattenAndWrapFiltersProvider); + const extractTimeFilter = Private(FilterBarLibExtractTimeFilterProvider); + const filterOutTimeBasedFilter = Private(FilterBarLibFilterOutTimeBasedFilterProvider); + const changeTimeFilter = Private(FilterBarLibChangeTimeFilterProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); + const privateFilterFieldRegex = /(^\$|meta)/; return { restrict: 'E', @@ -48,7 +48,7 @@ module.directive('filterBar', function (Private, Promise, getAppState) { $scope.aceLoaded = function (editor) { editor.$blockScrolling = Infinity; - let session = editor.getSession(); + const session = editor.getSession(); session.setTabSize(2); session.setUseSoftTabs(true); }; @@ -141,7 +141,7 @@ module.directive('filterBar', function (Private, Promise, getAppState) { } function updateFilters() { - let filters = queryFilter.getFilters(); + const filters = queryFilter.getFilters(); mapAndFlattenFilters(filters).then(function (results) { // used to display the current filters in the state $scope.filters = _.sortBy(results, function (filter) { diff --git a/src/ui/public/filter_bar/filter_bar_click_handler.js b/src/ui/public/filter_bar/filter_bar_click_handler.js index 25c7ae1a3b1bf..ce4a67696cd2b 100644 --- a/src/ui/public/filter_bar/filter_bar_click_handler.js +++ b/src/ui/public/filter_bar/filter_bar_click_handler.js @@ -6,7 +6,7 @@ import findByParam from 'ui/utils/find_by_param'; export default function (Notifier) { return function ($state) { return function (event, simulate) { - let notify = new Notifier({ + const notify = new Notifier({ location: 'Filter bar' }); let aggConfigResult; @@ -23,14 +23,14 @@ export default function (Notifier) { } if (aggConfigResult) { - let isLegendLabel = !!event.point.values; + const isLegendLabel = !!event.point.values; let aggBuckets = _.filter(aggConfigResult.getPath(), { type: 'bucket' }); // For legend clicks, use the last bucket in the path if (isLegendLabel) { // series data has multiple values, use aggConfig on the first // hierarchical data values is an object with the addConfig - let aggConfig = findByParam(event.point.values, 'aggConfig'); + const aggConfig = findByParam(event.point.values, 'aggConfig'); aggBuckets = aggBuckets.filter((result) => result.aggConfig && result.aggConfig === aggConfig); } diff --git a/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js b/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js index cd596f04f4188..a33a92f0a4bf9 100644 --- a/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js @@ -18,7 +18,7 @@ describe('Filter Bar Directive', function () { })); it('should change the timefilter to match the range gt/lt', function () { - let filter = { range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } }; + const filter = { range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } }; changeTimeFilter(filter); expect(timefilter.time.mode).to.be('absolute'); expect(moment.isMoment(timefilter.time.to)).to.be(true); @@ -28,7 +28,7 @@ describe('Filter Bar Directive', function () { }); it('should change the timefilter to match the range gte/lte', function () { - let filter = { range: { '@timestamp': { gte: 1388559600000, lte: 1388646000000 } } }; + const filter = { range: { '@timestamp': { gte: 1388559600000, lte: 1388646000000 } } }; changeTimeFilter(filter); expect(timefilter.time.mode).to.be('absolute'); expect(moment.isMoment(timefilter.time.to)).to.be(true); diff --git a/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js b/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js index fc953a1b34049..e09308fa0f402 100644 --- a/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js @@ -4,43 +4,43 @@ describe('Filter Bar Directive', function () { describe('dedupFilters(existing, filters)', function () { it('should return only filters which are not in the existing', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); it('should ignore the disabed attribute when comparing ', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { meta: { disabled: true }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); it('should ignore $state attribute', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { $state: { store: 'appState' }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { $state: { store: 'globalState' }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); diff --git a/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js b/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js index d38746497fd85..fa9cc9bca027d 100644 --- a/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { 'time': { gt: 1388559600000, lt: 1388646000000 } } } ]; @@ -34,7 +34,7 @@ describe('Filter Bar Directive', function () { }); it('should not return the non-matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } } ]; diff --git a/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js b/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js index 196b0acd2bc88..356ff3c06d1b9 100644 --- a/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js +++ b/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js @@ -3,13 +3,13 @@ import filterAppliedAndUnwrap from 'ui/filter_bar/lib/filter_applied_and_unwrap' describe('Filter Bar Directive', function () { describe('filterAppliedAndUnwrap()', function () { - let filters = [ + const filters = [ { meta: { apply: true }, exists: { field: '_type' } }, { meta: { apply: false }, query: { query_string: { query: 'foo:bar' } } } ]; it('should filter the applied and unwrap the filter', function () { - let results = filterAppliedAndUnwrap(filters); + const results = filterAppliedAndUnwrap(filters); expect(results).to.have.length(1); expect(results[0]).to.eql(filters[0]); }); diff --git a/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js b/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js index f4a23ce6dfc3b..97b6c99004644 100644 --- a/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { })); it('should return the matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { 'time': { gt: 1388559600000, lt: 1388646000000 } } } ]; diff --git a/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js b/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js index 6dc126c323a4d..43fb21bf7c7a0 100644 --- a/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js +++ b/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js @@ -19,13 +19,13 @@ describe('Filter Bar Directive', function () { it('should create a chaning function which calls the next function if the promise is rejected', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve('good')); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain(filter).then(function (result) { expect(result).to.be('good'); sinon.assert.calledOnce(next); @@ -35,12 +35,12 @@ describe('Filter Bar Directive', function () { }); it('should create a chaning function which DOES NOT call the next function if the result is resolved', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve('good')); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve('bad')); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain({}).then(function (result) { expect(result).to.be('good'); sinon.assert.notCalled(next); @@ -50,11 +50,11 @@ describe('Filter Bar Directive', function () { }); it('should resolve result for the mapping function', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve({ key: 'test', value: 'example' })); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); - let chain = mappingChainFn(next); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); + const chain = mappingChainFn(next); chain({}).then(function (result) { sinon.assert.notCalled(next); expect(result).to.eql({ key: 'test', value: 'example' }); @@ -64,11 +64,11 @@ describe('Filter Bar Directive', function () { }); it('should call the mapping function with the argument to the chain', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve({ key: 'test', value: 'example' })); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); - let chain = mappingChainFn(next); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); + const chain = mappingChainFn(next); chain({ test: 'example' }).then(function (result) { sinon.assert.calledOnce(mapping); expect(mapping.args[0][0]).to.eql({ test: 'example' }); @@ -80,13 +80,13 @@ describe('Filter Bar Directive', function () { }); it('should resolve result for the next function', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve({ key: 'test', value: 'example' })); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain(filter).then(function (result) { sinon.assert.calledOnce(mapping); sinon.assert.calledOnce(next); @@ -97,11 +97,11 @@ describe('Filter Bar Directive', function () { }); it('should reject with an error if no functions match', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let chain = mappingChainFn(); + const mappingChainFn = generateMappingChain(mapping); + const chain = mappingChainFn(); chain(filter).catch(function (err) { expect(err).to.be.an(Error); expect(err.message).to.be('No mappings have been found for filter.'); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js b/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js index e3eca25525df3..faf39d3d60f4a 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js @@ -21,7 +21,7 @@ describe('Filter Bar Directive', function () { $rootScope = _$rootScope_; })); - let filters = [ + const filters = [ null, [ { meta: { index: 'logstash-*' }, exists: { field: '_type' } }, diff --git a/src/ui/public/filter_bar/lib/__tests__/map_default.js b/src/ui/public/filter_bar/lib/__tests__/map_default.js index 3bc66ac578b24..721283f51a109 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_default.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_default.js @@ -13,7 +13,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { query: { match_all: {} } }; + const filter = { query: { match_all: {} } }; mapDefault(filter).then(function (result) { expect(result).to.have.property('key', 'query'); expect(result).to.have.property('value', '{"match_all":{}}'); @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { }); it('should work with undefined filter types', function (done) { - let filter = { + const filter = { 'bool': { 'must': { 'term': { @@ -41,7 +41,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined if there is no valid key', function (done) { - let filter = { meta: {} }; + const filter = { meta: {} }; mapDefault(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_exists.js b/src/ui/public/filter_bar/lib/__tests__/map_exists.js index aaaf417d5b2ac..5fea9cea76b54 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_exists.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_exists.js @@ -13,7 +13,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { exists: { field: '_type' } }; + const filter = { exists: { field: '_type' } }; mapExists(filter).then(function (result) { expect(result).to.have.property('key', 'exists'); expect(result).to.have.property('value', '_type'); @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapExists(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_filter.js b/src/ui/public/filter_bar/lib/__tests__/map_filter.js index 108bc7933cb26..52641afb8d238 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_filter.js @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { describe('mapFilter()', function () { it('should map query filters', function (done) { - let before = { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }; + const before = { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', '_type'); @@ -36,7 +36,7 @@ describe('Filter Bar Directive', function () { }); it('should map exists filters', function (done) { - let before = { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }; + const before = { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'exists'); @@ -49,7 +49,7 @@ describe('Filter Bar Directive', function () { }); it('should map missing filters', function (done) { - let before = { meta: { index: 'logstash-*' }, missing: { field: '@timestamp' } }; + const before = { meta: { index: 'logstash-*' }, missing: { field: '@timestamp' } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'missing'); @@ -62,7 +62,7 @@ describe('Filter Bar Directive', function () { }); it('should map json filter', function (done) { - let before = { meta: { index: 'logstash-*' }, query: { match_all: {} } }; + const before = { meta: { index: 'logstash-*' }, query: { match_all: {} } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'query'); @@ -75,7 +75,7 @@ describe('Filter Bar Directive', function () { }); it('should finish with a catch', function (done) { - let before = { meta: { index: 'logstash-*' }}; + const before = { meta: { index: 'logstash-*' }}; mapFilter(before).catch(function (error) { expect(error).to.be.an(Error); expect(error.message).to.be('No mappings have been found for filter.'); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js b/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js index c817825457802..59ab36e8414b8 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { $rootScope = _$rootScope_; })); - let filters = [ + const filters = [ null, [ { meta: { index: 'logstash-*' }, exists: { field: '_type' } }, diff --git a/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js b/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js index 96e891b9e8d2e..19d356a58059e 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters with bounds', function (done) { - let filter = { + const filter = { meta: { index: 'logstash-*' }, @@ -50,7 +50,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapGeoBoundingBox(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_missing.js b/src/ui/public/filter_bar/lib/__tests__/map_missing.js index 6f45c43528225..f3cecf7dec34e 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_missing.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_missing.js @@ -14,7 +14,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { missing: { field: '_type' } }; + const filter = { missing: { field: '_type' } }; mapMissing(filter).then(function (result) { expect(result).to.have.property('key', 'missing'); expect(result).to.have.property('value', '_type'); @@ -24,7 +24,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapMissing(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_query_string.js b/src/ui/public/filter_bar/lib/__tests__/map_query_string.js index 2913e0b77a860..41995d99608d6 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_query_string.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_query_string.js @@ -12,7 +12,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { query: { query_string: { query: 'foo:bar' } } }; + const filter = { query: { query_string: { query: 'foo:bar' } } }; mapQueryString(filter).then(function (result) { expect(result).to.have.property('key', 'query'); expect(result).to.have.property('value', 'foo:bar'); @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapQueryString(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_range.js b/src/ui/public/filter_bar/lib/__tests__/map_range.js index 85fff761b36c4..653aedee1665b 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_range.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_range.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters with gt/lt', function (done) { - let filter = { meta: { index: 'logstash-*' }, range: { bytes: { lt: 2048, gt: 1024 } } }; + const filter = { meta: { index: 'logstash-*' }, range: { bytes: { lt: 2048, gt: 1024 } } }; mapRange(filter).then(function (result) { expect(result).to.have.property('key', 'bytes'); expect(result).to.have.property('value', '1,024 to 2,048'); @@ -32,7 +32,7 @@ describe('Filter Bar Directive', function () { }); it('should return the key and value for matching filters with gte/lte', function (done) { - let filter = { meta: { index: 'logstash-*' }, range: { bytes: { lte: 2048, gte: 1024 } } }; + const filter = { meta: { index: 'logstash-*' }, range: { bytes: { lte: 2048, gte: 1024 } } }; mapRange(filter).then(function (result) { expect(result).to.have.property('key', 'bytes'); expect(result).to.have.property('value', '1,024 to 2,048'); @@ -42,7 +42,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapRange(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_script.js b/src/ui/public/filter_bar/lib/__tests__/map_script.js index 214b14b6e63d6..ee2d64fae62fd 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_script.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_script.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { + const filter = { meta: { index: 'logstash-*', field: 'script number' }, script: {script: { inline: 'doc["script number"].value * 5', params: { value: 35}}} }; @@ -35,7 +35,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapScript(filter).catch(function (result) { expect(result).to.be(filter); done(); @@ -44,7 +44,7 @@ describe('Filter Bar Directive', function () { }); it('should return a value for a range/histogram filter from a scripted field', (done) => { - let filter = { + const filter = { meta: { index: 'logstash-*', formattedValue: '1,000.00 to 2,000.00', diff --git a/src/ui/public/filter_bar/lib/__tests__/map_terms.js b/src/ui/public/filter_bar/lib/__tests__/map_terms.js index f2971ad91d7ce..aac44755000b8 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_terms.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_terms.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }; + const filter = { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }; mapTerms(filter).then(function (result) { expect(result).to.have.property('key', '_type'); expect(result).to.have.property('value', 'apache'); @@ -32,7 +32,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapTerms(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/only_disabled.js b/src/ui/public/filter_bar/lib/__tests__/only_disabled.js index e7bc342a5d8b1..f9e170b9afd1d 100644 --- a/src/ui/public/filter_bar/lib/__tests__/only_disabled.js +++ b/src/ui/public/filter_bar/lib/__tests__/only_disabled.js @@ -4,71 +4,71 @@ describe('Filter Bar Directive', function () { describe('onlyDisabled()', function () { it('should return true if all filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: true } }]; + const newFilters = [{ meta: { disabled: true } }]; expect(onlyDisabled(newFilters, filters)).to.be(true); }); it('should return false if all filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false if only old filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false if new filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = [{ meta: { disabled: true } }]; + const newFilters = [{ meta: { disabled: true } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return true when all removed filters were disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(true); }); it('should return false when all removed filters were not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return true if all changed filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true, negate: false } }, { meta: { disabled: true, negate: false } } ]; - let newFilters = [ + const newFilters = [ { meta: { disabled: true, negate: true } }, { meta: { disabled: true, negate: true } } ]; @@ -76,31 +76,31 @@ describe('Filter Bar Directive', function () { }); it('should return false if all filters remove were not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false when all removed filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: false } }, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should not throw with null filters', function () { - let filters = [ + const filters = [ null, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(function () { onlyDisabled(newFilters, filters); }).to.not.throwError(); diff --git a/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js b/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js index 391b2dc67dc65..dffe89f96f3c1 100644 --- a/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js @@ -4,16 +4,16 @@ describe('Filter Bar Directive', function () { describe('uniqFilter', function () { it('should filter out dups', function () { - let before = [ + const before = [ { query: { _type: { match: { query: 'apache', type: 'phrase' } } } }, { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); it('should filter out duplicates, ignoring meta attributes', function () { - let before = [ + const before = [ { meta: { negate: true }, query: { _type: { match: { query: 'apache', type: 'phrase' } } } @@ -23,12 +23,12 @@ describe('Filter Bar Directive', function () { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); it('should filter out duplicates, ignoring $state attributes', function () { - let before = [ + const before = [ { $state: { store: 'appState' }, query: { _type: { match: { query: 'apache', type: 'phrase' } } } @@ -38,7 +38,7 @@ describe('Filter Bar Directive', function () { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); }); diff --git a/src/ui/public/filter_bar/lib/change_time_filter.js b/src/ui/public/filter_bar/lib/change_time_filter.js index 47e991eabe7be..cee9477f09edc 100644 --- a/src/ui/public/filter_bar/lib/change_time_filter.js +++ b/src/ui/public/filter_bar/lib/change_time_filter.js @@ -2,8 +2,8 @@ import moment from 'moment'; import _ from 'lodash'; export default function changeTimeFilterProvider(timefilter) { return function (filter) { - let key = _.keys(filter.range)[0]; - let values = filter.range[key]; + const key = _.keys(filter.range)[0]; + const values = filter.range[key]; timefilter.time.from = moment(values.gt || values.gte); timefilter.time.to = moment(values.lt || values.lte); timefilter.time.mode = 'absolute'; diff --git a/src/ui/public/filter_bar/lib/compare_filters.js b/src/ui/public/filter_bar/lib/compare_filters.js index 2cfa19e6d5345..3c903ba19c8f2 100644 --- a/src/ui/public/filter_bar/lib/compare_filters.js +++ b/src/ui/public/filter_bar/lib/compare_filters.js @@ -24,7 +24,7 @@ export default function (first, second, comparatorOptions) { }; function mapFilter(filter) { - let cleaned = _.omit(filter, excludedAttributes); + const cleaned = _.omit(filter, excludedAttributes); if (comparators.negate) cleaned.negate = filter.meta && !!filter.meta.negate; if (comparators.disabled) cleaned.disabled = filter.meta && !!filter.meta.disabled; return cleaned; diff --git a/src/ui/public/filter_bar/lib/extract_time_filter.js b/src/ui/public/filter_bar/lib/extract_time_filter.js index c13b96a4ffa25..a905cbf593c5d 100644 --- a/src/ui/public/filter_bar/lib/extract_time_filter.js +++ b/src/ui/public/filter_bar/lib/extract_time_filter.js @@ -3,12 +3,12 @@ export default function extractTimeFilterProvider(courier, Promise) { return Promise.method(function (filters) { // Assume all the index patterns are the same since they will be added // from the same visualization. - let id = _.get(filters, '[0].meta.index'); + const id = _.get(filters, '[0].meta.index'); if (id == null) return; return courier.indexPatterns.get(id).then(function (indexPattern) { - let filter = _.find(filters, function (obj) { - let key = _.keys(obj.range)[0]; + const filter = _.find(filters, function (obj) { + const key = _.keys(obj.range)[0]; return key === indexPattern.timeFieldName; }); if (filter && filter.range) { diff --git a/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js b/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js index bd033b15fd8d5..91299918558a2 100644 --- a/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js +++ b/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function filterOutTimeBaseFilter(courier, Promise) { return Promise.method(function (filters) { - let id = _.get(filters, '[0].meta.index'); + const id = _.get(filters, '[0].meta.index'); if (id == null) return; return courier.indexPatterns.get(id).then(function (indexPattern) { diff --git a/src/ui/public/filter_bar/lib/generate_mapping_chain.js b/src/ui/public/filter_bar/lib/generate_mapping_chain.js index e857804a37775..f27f4a50e2c1e 100644 --- a/src/ui/public/filter_bar/lib/generate_mapping_chain.js +++ b/src/ui/public/filter_bar/lib/generate_mapping_chain.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function generateMappingChainProvider(Promise) { - let noop = function () { + const noop = function () { return Promise.reject(new Error('No mappings have been found for filter.')); }; diff --git a/src/ui/public/filter_bar/lib/map_and_flatten_filters.js b/src/ui/public/filter_bar/lib/map_and_flatten_filters.js index f48706eb68f88..ebaf8043e2f65 100644 --- a/src/ui/public/filter_bar/lib/map_and_flatten_filters.js +++ b/src/ui/public/filter_bar/lib/map_and_flatten_filters.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import FilterBarLibMapFilterProvider from 'ui/filter_bar/lib/map_filter'; export default function mapAndFlattenFiltersProvider(Private, Promise) { - let mapFilter = Private(FilterBarLibMapFilterProvider); + const mapFilter = Private(FilterBarLibMapFilterProvider); return function (filters) { return _(filters) .flatten() diff --git a/src/ui/public/filter_bar/lib/map_default.js b/src/ui/public/filter_bar/lib/map_default.js index e9f53ed21710e..45a3a2f84071d 100644 --- a/src/ui/public/filter_bar/lib/map_default.js +++ b/src/ui/public/filter_bar/lib/map_default.js @@ -2,15 +2,15 @@ import angular from 'angular'; import _ from 'lodash'; export default function mapDefaultProvider(Promise) { - let metaProperty = /(^\$|meta)/; + const metaProperty = /(^\$|meta)/; return function (filter) { - let key = _.find(_.keys(filter), function (key) { + const key = _.find(_.keys(filter), function (key) { return !key.match(metaProperty); }); if (key) { - let value = angular.toJson(filter[key]); + const value = angular.toJson(filter[key]); return Promise.resolve({ key: key, value: value }); } return Promise.reject(filter); diff --git a/src/ui/public/filter_bar/lib/map_filter.js b/src/ui/public/filter_bar/lib/map_filter.js index 5ff047813f9ef..76e317fb96b0d 100644 --- a/src/ui/public/filter_bar/lib/map_filter.js +++ b/src/ui/public/filter_bar/lib/map_filter.js @@ -11,7 +11,7 @@ import MapScriptProvider from './map_script'; import MapDefaultProvider from './map_default'; export default function mapFilterProvider(Promise, Private) { - let generateMappingChain = Private(GenerateMappingChainProvider); + const generateMappingChain = Private(GenerateMappingChainProvider); /** Mappers **/ @@ -29,7 +29,7 @@ export default function mapFilterProvider(Promise, Private) { // To create a new mapper you just need to create a function // that either handles the mapping operation or not // and add it here. ProTip: These are executed in order listed - let mappers = [ + const mappers = [ Private(MapMatchAllProvider), Private(MapTermsProvider), Private(MapRangeProvider), @@ -41,14 +41,14 @@ export default function mapFilterProvider(Promise, Private) { Private(MapDefaultProvider) ]; - let noop = function () { + const noop = function () { return Promise.reject(new Error('No mappings have been found for filter.')); }; // Create a chain of responsibility by reducing all the // mappers down into one function. - let mapFn = _.reduceRight(mappers, function (memo, map) { - let filterChainFn = generateMappingChain(map); + const mapFn = _.reduceRight(mappers, function (memo, map) { + const filterChainFn = generateMappingChain(map); return filterChainFn(memo); }, noop); diff --git a/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js b/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js index f86b5a6e566b1..fb2d0707deafb 100644 --- a/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js +++ b/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import FilterBarLibMapAndFlattenFiltersProvider from 'ui/filter_bar/lib/map_and_flatten_filters'; export default function mapFlattenAndWrapFilters(Private) { - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); return function (filters) { return mapAndFlattenFilters(filters).then(function (filters) { return _.map(filters, function (filter) { diff --git a/src/ui/public/filter_bar/lib/map_range.js b/src/ui/public/filter_bar/lib/map_range.js index 5e710b0dd4560..8eeb93eb7c4fc 100644 --- a/src/ui/public/filter_bar/lib/map_range.js +++ b/src/ui/public/filter_bar/lib/map_range.js @@ -7,9 +7,9 @@ export default function mapRangeProvider(Promise, courier) { .indexPatterns .get(filter.meta.index) .then(function (indexPattern) { - let key = Object.keys(filter.range)[0]; - let convert = indexPattern.fields.byName[key].format.getConverterFor('text'); - let range = filter.range[key]; + const key = Object.keys(filter.range)[0]; + const convert = indexPattern.fields.byName[key].format.getConverterFor('text'); + const range = filter.range[key]; let left = has(range, 'gte') ? range.gte : range.gt; if (left == null) left = -Infinity; diff --git a/src/ui/public/filter_bar/lib/only_disabled.js b/src/ui/public/filter_bar/lib/only_disabled.js index 8bb7cbf23ee91..2513e0ba25566 100644 --- a/src/ui/public/filter_bar/lib/only_disabled.js +++ b/src/ui/public/filter_bar/lib/only_disabled.js @@ -1,6 +1,6 @@ import _ from 'lodash'; -let pluckDisabled = function (filter) { +const pluckDisabled = function (filter) { return _.get(filter, 'meta.disabled'); }; diff --git a/src/ui/public/filter_bar/lib/only_state_changed.js b/src/ui/public/filter_bar/lib/only_state_changed.js index 8fe0cceec830a..048e20929e6c9 100644 --- a/src/ui/public/filter_bar/lib/only_state_changed.js +++ b/src/ui/public/filter_bar/lib/only_state_changed.js @@ -1,6 +1,6 @@ import _ from 'lodash'; import compareFilters from 'ui/filter_bar/lib/compare_filters'; -let compareOptions = { disabled: true, negate: true }; +const compareOptions = { disabled: true, negate: true }; /** * Checks to see if only disabled filters have been changed @@ -8,7 +8,7 @@ let compareOptions = { disabled: true, negate: true }; */ export default function (newFilters, oldFilters) { return _.every(newFilters, function (newFilter, i) { - let match = _.find(oldFilters, function (oldFilter) { + const match = _.find(oldFilters, function (oldFilter) { return compareFilters(newFilter, oldFilter, compareOptions); }); return !!match; diff --git a/src/ui/public/filter_bar/push_filter.js b/src/ui/public/filter_bar/push_filter.js index 6375791b05826..95e524b8074f2 100644 --- a/src/ui/public/filter_bar/push_filter.js +++ b/src/ui/public/filter_bar/push_filter.js @@ -7,8 +7,8 @@ export default function () { // Hierarchical and tabular data set their aggConfigResult parameter // differently because of how the point is rewritten between the two. So // we need to check if the point.orig is set, if not use try the point.aggConfigResult - let filters = _.clone($state.filters || []); - let pendingFilter = { meta: { negate: negate, index: index }}; + const filters = _.clone($state.filters || []); + const pendingFilter = { meta: { negate: negate, index: index }}; _.extend(pendingFilter, filter); filters.push(pendingFilter); $state.filters = filters; diff --git a/src/ui/public/filter_bar/query_filter.js b/src/ui/public/filter_bar/query_filter.js index 7647586b0c44f..679bb66fcb432 100644 --- a/src/ui/public/filter_bar/query_filter.js +++ b/src/ui/public/filter_bar/query_filter.js @@ -8,21 +8,21 @@ import EventsProvider from 'ui/events'; import FilterBarLibMapAndFlattenFiltersProvider from 'ui/filter_bar/lib/map_and_flatten_filters'; export default function (Private, $rootScope, getAppState, globalState, config) { - let EventEmitter = Private(EventsProvider); - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const EventEmitter = Private(EventsProvider); + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); - let queryFilter = new EventEmitter(); + const queryFilter = new EventEmitter(); queryFilter.getFilters = function () { - let compareOptions = { disabled: true, negate: true }; - let appFilters = queryFilter.getAppFilters(); - let globalFilters = queryFilter.getGlobalFilters(); + const compareOptions = { disabled: true, negate: true }; + const appFilters = queryFilter.getAppFilters(); + const globalFilters = queryFilter.getGlobalFilters(); return uniqFilters(globalFilters.concat(appFilters), compareOptions); }; queryFilter.getAppFilters = function () { - let appState = getAppState(); + const appState = getAppState(); if (!appState || !appState.filters) return []; // Work around for https://github.com/elastic/kibana/issues/5896 @@ -49,7 +49,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) queryFilter.addFilters = function (filters, global) { if (global === undefined) { - let configDefault = config.get('filters:pinnedByDefault'); + const configDefault = config.get('filters:pinnedByDefault'); if (configDefault === false || configDefault === true) { global = configDefault; @@ -57,8 +57,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) } // Determine the state for the new filter (whether to pass the filter through other apps or not) - let appState = getAppState(); - let filterState = (global) ? globalState : appState; + const appState = getAppState(); + const filterState = (global) ? globalState : appState; if (!_.isArray(filters)) { filters = [filters]; @@ -79,8 +79,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @param {object} matchFilter The filter to remove */ queryFilter.removeFilter = function (matchFilter) { - let appState = getAppState(); - let filter = _.omit(matchFilter, ['$$hashKey']); + const appState = getAppState(); + const filter = _.omit(matchFilter, ['$$hashKey']); let state; let index; @@ -108,11 +108,11 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} Promise that resolves to the new filter on a successful merge */ queryFilter.updateFilter = function (filter) { - let mergedFilter = _.assign({}, filter.source, filter.model); + const mergedFilter = _.assign({}, filter.source, filter.model); mergedFilter.meta.alias = filter.alias; //If the filter type is changed we want to discard the old type //when merging changes back in - let filterTypeReplaced = filter.model[filter.type] !== mergedFilter[filter.type]; + const filterTypeReplaced = filter.model[filter.type] !== mergedFilter[filter.type]; if (filterTypeReplaced) { delete mergedFilter[filter.type]; } @@ -124,7 +124,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * Removes all filters */ queryFilter.removeAll = function () { - let appState = getAppState(); + const appState = getAppState(); appState.filters = []; globalState.filters = []; }; @@ -137,7 +137,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) */ queryFilter.toggleFilter = function (filter, force) { // Toggle the disabled flag - let disabled = _.isUndefined(force) ? !filter.meta.disabled : !!force; + const disabled = _.isUndefined(force) ? !filter.meta.disabled : !!force; filter.meta.disabled = disabled; return filter; }; @@ -182,20 +182,20 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} updated filter */ queryFilter.pinFilter = function (filter, force) { - let appState = getAppState(); + const appState = getAppState(); if (!appState) return filter; // ensure that both states have a filters property if (!_.isArray(globalState.filters)) globalState.filters = []; if (!_.isArray(appState.filters)) appState.filters = []; - let appIndex = _.indexOf(appState.filters, filter); + const appIndex = _.indexOf(appState.filters, filter); if (appIndex !== -1 && force !== false) { appState.filters.splice(appIndex, 1); globalState.filters.push(filter); } else { - let globalIndex = _.indexOf(globalState.filters, filter); + const globalIndex = _.indexOf(globalState.filters, filter); if (globalIndex === -1 || force === true) return filter; @@ -226,7 +226,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * Rids filter list of null values and replaces state if any nulls are found */ function validateStateFilters(state) { - let compacted = _.compact(state.filters); + const compacted = _.compact(state.filters); if (state.filters.length !== compacted.length) { state.filters = compacted; state.replace(); @@ -240,7 +240,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} Resulting filter list, app and global combined */ function saveState() { - let appState = getAppState(); + const appState = getAppState(); if (appState) appState.save(); globalState.save(); } @@ -256,7 +256,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) // helper to run a function on all filters in all states function executeOnFilters(fn) { - let appState = getAppState(); + const appState = getAppState(); let globalFilters = []; let appFilters = []; @@ -268,13 +268,13 @@ export default function (Private, $rootScope, getAppState, globalState, config) function mergeStateFilters(gFilters, aFilters, compareOptions) { // ensure we don't mutate the filters passed in - let globalFilters = gFilters ? _.cloneDeep(gFilters) : []; - let appFilters = aFilters ? _.cloneDeep(aFilters) : []; + const globalFilters = gFilters ? _.cloneDeep(gFilters) : []; + const appFilters = aFilters ? _.cloneDeep(aFilters) : []; compareOptions = _.defaults(compareOptions || {}, { disabled: true }); // existing globalFilters should be mutated by appFilters _.each(appFilters, function (filter, i) { - let match = _.find(globalFilters, function (globalFilter) { + const match = _.find(globalFilters, function (globalFilter) { return compareFilters(globalFilter, filter, compareOptions); }); @@ -306,7 +306,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) function initAppStateWatchers() { // multi watch on the app and global states - let stateWatchers = [{ + const stateWatchers = [{ fn: $rootScope.$watch, deep: true, get: queryFilter.getGlobalFilters @@ -325,14 +325,14 @@ export default function (Private, $rootScope, getAppState, globalState, config) let doFetch = false; // reconcile filter in global and app states - let filters = mergeStateFilters(next[0], next[1]); - let globalFilters = filters[0]; - let appFilters = filters[1]; - let appState = getAppState(); + const filters = mergeStateFilters(next[0], next[1]); + const globalFilters = filters[0]; + const appFilters = filters[1]; + const appState = getAppState(); // save the state, as it may have updated - let globalChanged = !_.isEqual(next[0], globalFilters); - let appChanged = !_.isEqual(next[1], appFilters); + const globalChanged = !_.isEqual(next[0], globalFilters); + const appChanged = !_.isEqual(next[1], appFilters); // the filters were changed, apply to state (re-triggers this watcher) if (globalChanged || appChanged) { @@ -359,8 +359,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) let oldFilters = []; stateWatchers.forEach(function (watcher, i) { - let nextVal = next[i]; - let prevVal = prev[i]; + const nextVal = next[i]; + const prevVal = prev[i]; newFilters = newFilters.concat(nextVal); oldFilters = oldFilters.concat(prevVal); diff --git a/src/ui/public/filter_manager/__tests__/filter_manager.js b/src/ui/public/filter_manager/__tests__/filter_manager.js index 618b969b9589b..29f20a1e6b109 100644 --- a/src/ui/public/filter_manager/__tests__/filter_manager.js +++ b/src/ui/public/filter_manager/__tests__/filter_manager.js @@ -12,7 +12,7 @@ let appState; function checkAddFilters(length, comps, idx) { idx = idx || 0; - let filters = queryFilter.addFilters.getCall(idx).args[0]; + const filters = queryFilter.addFilters.getCall(idx).args[0]; expect(filters.length).to.be(length); if (!_.isArray(comps)) return; @@ -114,7 +114,7 @@ describe('Filter Manager', function () { checkAddFilters(0, null, 3); expect(appState.filters).to.have.length(2); - let scriptedField = {name: 'scriptedField', scripted: true, script: 1}; + const scriptedField = {name: 'scriptedField', scripted: true, script: 1}; filterManager.add(scriptedField, 1, '+', 'myIndex'); checkAddFilters(1, [{ meta: {index: 'myIndex', negate: false, field: 'scriptedField'}, diff --git a/src/ui/public/filter_manager/filter_manager.js b/src/ui/public/filter_manager/filter_manager.js index c856ab0c07746..0d485745301db 100644 --- a/src/ui/public/filter_manager/filter_manager.js +++ b/src/ui/public/filter_manager/filter_manager.js @@ -2,21 +2,21 @@ import _ from 'lodash'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; // Adds a filter to a passed state export default function (Private) { - let queryFilter = Private(FilterBarQueryFilterProvider); - let filterManager = {}; + const queryFilter = Private(FilterBarQueryFilterProvider); + const filterManager = {}; filterManager.add = function (field, values, operation, index) { values = _.isArray(values) ? values : [values]; - let fieldName = _.isObject(field) ? field.name : field; - let filters = _.flatten([queryFilter.getAppFilters()]); - let newFilters = []; + const fieldName = _.isObject(field) ? field.name : field; + const filters = _.flatten([queryFilter.getAppFilters()]); + const newFilters = []; - let negate = (operation === '-'); + const negate = (operation === '-'); // TODO: On array fields, negating does not negate the combination, rather all terms _.each(values, function (value) { let filter; - let existing = _.find(filters, function (filter) { + const existing = _.find(filters, function (filter) { if (!filter) return; if (fieldName === '_exists_' && filter.exists) { diff --git a/src/ui/public/filter_manager/lib/__tests__/range.js b/src/ui/public/filter_manager/lib/__tests__/range.js index 94bee0426f4b6..4b138edd012ed 100644 --- a/src/ui/public/filter_manager/lib/__tests__/range.js +++ b/src/ui/public/filter_manager/lib/__tests__/range.js @@ -54,9 +54,9 @@ describe('Filter Manager', function () { it('to use the right operator for each of gte, gt, lt and lte', function () { _.each({gte: '>=', gt: '>', lte: '<=', lt: '<'}, function (operator, key) { - let params = {}; + const params = {}; params[key] = 5; - let filter = fn(indexPattern.fields.byName['script number'], params, indexPattern); + const filter = fn(indexPattern.fields.byName['script number'], params, indexPattern); expect(filter.script.script.inline).to.be('(' + indexPattern.fields.byName['script number'].script + ')' + operator + key); expect(filter.script.script.params[key]).to.be(5); diff --git a/src/ui/public/filter_manager/lib/phrase.js b/src/ui/public/filter_manager/lib/phrase.js index fbc2f45657d01..5a1abeedc1f45 100644 --- a/src/ui/public/filter_manager/lib/phrase.js +++ b/src/ui/public/filter_manager/lib/phrase.js @@ -1,6 +1,6 @@ import _ from 'lodash'; export default function buildPhraseFilter(field, value, indexPattern) { - let filter = { meta: { index: indexPattern.id} }; + const filter = { meta: { index: indexPattern.id} }; if (field.scripted) { _.set(filter, 'script.script', { diff --git a/src/ui/public/filters/__tests__/field_type.js b/src/ui/public/filters/__tests__/field_type.js index 215a34be2c206..fb4676ddfd594 100644 --- a/src/ui/public/filters/__tests__/field_type.js +++ b/src/ui/public/filters/__tests__/field_type.js @@ -9,7 +9,7 @@ let filter; let types; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); @@ -59,7 +59,7 @@ describe('fieldType array filter', function () { }); it('should allow negation', function () { - let resultNames = _.pluck(filter(types, '!string'), 'name'); + const resultNames = _.pluck(filter(types, '!string'), 'name'); expect(resultNames).to.eql(['n1', 'n2', 'i1', 'd1']); }); }); diff --git a/src/ui/public/filters/__tests__/label.js b/src/ui/public/filters/__tests__/label.js index 920f6fb90f0bd..db604c0fc6413 100644 --- a/src/ui/public/filters/__tests__/label.js +++ b/src/ui/public/filters/__tests__/label.js @@ -9,7 +9,7 @@ import 'plugins/kibana/discover/index'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/moment.js b/src/ui/public/filters/__tests__/moment.js index 1d4a330251e5b..fb05c6e2fb604 100644 --- a/src/ui/public/filters/__tests__/moment.js +++ b/src/ui/public/filters/__tests__/moment.js @@ -9,10 +9,10 @@ import 'ui/filters/moment'; let filter; let config; -let anchor = '2014-01-01T06:06:06.666'; +const anchor = '2014-01-01T06:06:06.666'; let clock; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/rison.js b/src/ui/public/filters/__tests__/rison.js index 2412d032da994..9e720bcf9a7d4 100644 --- a/src/ui/public/filters/__tests__/rison.js +++ b/src/ui/public/filters/__tests__/rison.js @@ -8,7 +8,7 @@ import 'plugins/kibana/discover/index'; let rison; let risonDecode; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); @@ -20,13 +20,13 @@ let init = function (expandable) { }; describe('rison filters', function () { - let testObj = { + const testObj = { time: { from: 'now-15m', to: 'now' } }; - let testRison = '(time:(from:now-15m,to:now))'; + const testRison = '(time:(from:now-15m,to:now))'; beforeEach(function () { init(); diff --git a/src/ui/public/filters/__tests__/short_dots.js b/src/ui/public/filters/__tests__/short_dots.js index cacfab16b8676..acd92001e0cb0 100644 --- a/src/ui/public/filters/__tests__/short_dots.js +++ b/src/ui/public/filters/__tests__/short_dots.js @@ -10,7 +10,7 @@ let filter; let config; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/start_from.js b/src/ui/public/filters/__tests__/start_from.js index 3f03605c27f3d..2377a06fd82fb 100644 --- a/src/ui/public/filters/__tests__/start_from.js +++ b/src/ui/public/filters/__tests__/start_from.js @@ -6,7 +6,7 @@ import 'ui/filters/start_from'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/uriescape.js b/src/ui/public/filters/__tests__/uriescape.js index 8baa7469ccf5c..4a1acfb404d29 100644 --- a/src/ui/public/filters/__tests__/uriescape.js +++ b/src/ui/public/filters/__tests__/uriescape.js @@ -7,7 +7,7 @@ import 'plugins/kibana/discover/index'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/_prop_filter.js b/src/ui/public/filters/_prop_filter.js index 19d817df80662..f2893127edf9b 100644 --- a/src/ui/public/filters/_prop_filter.js +++ b/src/ui/public/filters/_prop_filter.js @@ -23,7 +23,7 @@ function propFilter(prop) { if (!_.isArray(filters)) filters = filters.split(','); if (_.contains(filters, '*')) return list; - let options = filters.reduce(function (options, filter) { + const options = filters.reduce(function (options, filter) { let type = 'include'; let value = filter; @@ -38,12 +38,12 @@ function propFilter(prop) { }, {}); return list.filter(function (item) { - let value = item[prop]; + const value = item[prop]; - let excluded = options.exclude && _.contains(options.exclude, value); + const excluded = options.exclude && _.contains(options.exclude, value); if (excluded) return false; - let included = !options.include || _.contains(options.include, value); + const included = !options.include || _.contains(options.include, value); if (included) return true; return false; diff --git a/src/ui/public/filters/comma_list.js b/src/ui/public/filters/comma_list.js index febe90384585f..2b5943dae3100 100644 --- a/src/ui/public/filters/comma_list.js +++ b/src/ui/public/filters/comma_list.js @@ -13,12 +13,12 @@ uiModules * @return {String} */ return function (input, inclusive) { - let list = _.commaSeperatedList(input); + const list = _.commaSeperatedList(input); if (list.length < 2) { return list.join(''); } - let conj = inclusive ? ' and ' : ' or '; + const conj = inclusive ? ' and ' : ' or '; return list.slice(0, -1).join(', ') + conj + _.last(list); }; diff --git a/src/ui/public/filters/rison.js b/src/ui/public/filters/rison.js index a41864390dc76..264fef2373a78 100644 --- a/src/ui/public/filters/rison.js +++ b/src/ui/public/filters/rison.js @@ -1,6 +1,6 @@ import rison from 'rison-node'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.filter('rison', function () { return function (str) { diff --git a/src/ui/public/filters/trust_as_html.js b/src/ui/public/filters/trust_as_html.js index e622294557d33..428a5d82d800c 100644 --- a/src/ui/public/filters/trust_as_html.js +++ b/src/ui/public/filters/trust_as_html.js @@ -1,6 +1,6 @@ import angular from 'angular'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // Simple filter to allow using ng-bind-html without explicitly calling $sce.trustAsHtml in a controller // (See http://goo.gl/mpj9o2) diff --git a/src/ui/public/filters/unique.js b/src/ui/public/filters/unique.js index 643ae819f591d..e85087ecb1ba8 100644 --- a/src/ui/public/filters/unique.js +++ b/src/ui/public/filters/unique.js @@ -6,7 +6,7 @@ uiModules .get('kibana') .filter('unique', function () { return function (arr) { - let list = _.unique(arr); + const list = _.unique(arr); return list; }; }); diff --git a/src/ui/public/highlight/__tests__/highlight.js b/src/ui/public/highlight/__tests__/highlight.js index 050cd99d92c27..6c71e73ec12fe 100644 --- a/src/ui/public/highlight/__tests__/highlight.js +++ b/src/ui/public/highlight/__tests__/highlight.js @@ -15,7 +15,7 @@ describe('Highlight', function () { tags = highlightTags; })); - let text = '' + + const text = '' + 'Bacon ipsum dolor amet pork loin pork cow pig beef chuck ground round shankle sirloin landjaeger kevin ' + 'venison sausage ribeye tongue. Chicken bacon ball tip pork. Brisket pork capicola spare ribs pastrami rump ' + 'sirloin, t-bone ham shoulder jerky turducken bresaola. Chicken cow beef picanha. Picanha hamburger alcatra ' + @@ -28,27 +28,27 @@ describe('Highlight', function () { }); it('should highlight a single result', function () { - let highlights = [ + const highlights = [ tags.pre + 'hamburger' + tags.post + ' alcatra cupim. Salami capicola boudin pork belly shank picanha.' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('hamburger')).to.be.greaterThan(-1); expect(result.split('hamburger').length).to.be(text.split('hamburger').length); }); it('should highlight multiple results', function () { - let highlights = [ + const highlights = [ 'kevin venison sausage ribeye tongue. ' + tags.pre + 'Chicken' + tags.post + ' bacon ball tip pork. Brisket ' + 'pork capicola spare ribs pastrami rump sirloin, t-bone ham shoulder jerky turducken bresaola. ' + tags.pre + 'Chicken' + tags.post + ' cow beef picanha. Picanha' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('Chicken')).to.be.greaterThan(-1); expect(result.split('Chicken').length).to.be(text.split('Chicken').length); }); it('should highlight multiple hits in a result', function () { - let highlights = [ + const highlights = [ 'Bacon ipsum dolor amet ' + tags.pre + 'pork' + tags.post + ' loin ' + '' + tags.pre + 'pork' + tags.post + ' cow pig beef chuck ground round shankle ' + 'sirloin landjaeger', @@ -58,14 +58,14 @@ describe('Highlight', function () { 'hamburger alcatra cupim. Salami capicola boudin ' + tags.pre + 'pork' + tags.post + ' ' + 'belly shank picanha.' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('pork')).to.be.greaterThan(-1); expect(result.split('pork').length).to.be(text.split('pork').length); }); it('should accept an object and return a string containing its properties', function () { - let obj = {foo: 1, bar: 2}; - let result = filter(obj, null); + const obj = {foo: 1, bar: 2}; + const result = filter(obj, null); expect(result.indexOf('' + obj)).to.be(-1); expect(result.indexOf('foo')).to.be.greaterThan(-1); expect(result.indexOf('bar')).to.be.greaterThan(-1); diff --git a/src/ui/public/highlight/highlight.js b/src/ui/public/highlight/highlight.js index f51a3ae2bfb52..e75d433e8a6d1 100644 --- a/src/ui/public/highlight/highlight.js +++ b/src/ui/public/highlight/highlight.js @@ -3,7 +3,7 @@ import _ from 'lodash'; import angular from 'angular'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.filter('highlight', function (highlightTags) { return function (formatted, highlight) { @@ -13,12 +13,12 @@ module.filter('highlight', function (highlightTags) { section = _.escape(section); // Strip out the highlight tags to compare against the formatted string - let untagged = section + const untagged = section .split(highlightTags.pre).join('') .split(highlightTags.post).join(''); // Replace all highlight tags with proper html tags - let tagged = section + const tagged = section .split(highlightTags.pre).join('') .split(highlightTags.post).join(''); diff --git a/src/ui/public/highlight/highlight_tags.js b/src/ui/public/highlight/highlight_tags.js index 350357ec35b59..19e8a26c43a12 100644 --- a/src/ui/public/highlight/highlight_tags.js +++ b/src/ui/public/highlight/highlight_tags.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // By default, ElasticSearch surrounds matched values in . This is not ideal because it is possible that // the value could contain in the value. We define these custom tags that we would never expect to see diff --git a/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js b/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js index 60a4b93ba6d77..773f2970fad7f 100644 --- a/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js +++ b/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js @@ -20,7 +20,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should cast numeric types to "number"', function () { - let types = [ + const types = [ 'float', 'double', 'integer', @@ -36,7 +36,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should treat non-numeric known types as what they are', function () { - let types = [ + const types = [ 'date', 'boolean', 'ip', @@ -53,7 +53,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should cast text and keyword types to "string"', function () { - let types = [ + const types = [ 'keyword', 'text' ]; diff --git a/src/ui/public/index_patterns/__tests__/_field_format.js b/src/ui/public/index_patterns/__tests__/_field_format.js index fd8eb22e9dd97..ca8fb8d90fcdf 100644 --- a/src/ui/public/index_patterns/__tests__/_field_format.js +++ b/src/ui/public/index_patterns/__tests__/_field_format.js @@ -24,14 +24,14 @@ describe('FieldFormat class', function () { describe('params', function () { it('accepts its params via the constructor', function () { - let f = new TestFormat({ foo: 'bar' }); + const f = new TestFormat({ foo: 'bar' }); expect(f.param('foo')).to.be('bar'); }); it('allows reading a clone of the params', function () { - let params = { foo: 'bar' }; - let f = new TestFormat(params); - let output = f.params(); + const params = { foo: 'bar' }; + const f = new TestFormat(params); + const output = f.params(); expect(output).to.eql(params); expect(output).to.not.be(params); }); @@ -39,29 +39,29 @@ describe('FieldFormat class', function () { describe('type', function () { it('links the constructor class to instances as the `type`', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.type).to.be(TestFormat); }); }); describe('toJSON', function () { it('serializes to a version a basic id and param pair', function () { - let f = new TestFormat({ foo: 'bar' }); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat({ foo: 'bar' }); + const ser = JSON.parse(JSON.stringify(f)); expect(ser).to.eql({ id: 'test-format', params: { foo: 'bar' } }); }); it('removes param values that match the defaults', function () { TestFormat.paramDefaults = { foo: 'bar' }; - let f = new TestFormat({ foo: 'bar', baz: 'bar' }); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat({ foo: 'bar', baz: 'bar' }); + const ser = JSON.parse(JSON.stringify(f)); expect(ser.params).to.eql({ baz: 'bar' }); }); it('removes the params entirely if they are empty', function () { - let f = new TestFormat(); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat(); + const ser = JSON.parse(JSON.stringify(f)); expect(ser).to.not.have.property('params'); }); }); @@ -69,7 +69,7 @@ describe('FieldFormat class', function () { describe('converters', function () { describe('#getConverterFor', function () { it('returns a converter for a specific content type', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.getConverterFor('html')()).to.be.a('string'); expect(f.getConverterFor('text')()).to.be.a('string'); }); @@ -81,9 +81,9 @@ describe('FieldFormat class', function () { return 'formatted'; }; - let f = new TestFormat(); - let text = f.getConverterFor('text'); - let html = f.getConverterFor('html'); + const f = new TestFormat(); + const text = f.getConverterFor('text'); + const html = f.getConverterFor('html'); expect(text).to.not.be(html); expect(text('formatted')).to.be('formatted'); expect(html('formatted')).to.be('formatted'); @@ -95,9 +95,9 @@ describe('FieldFormat class', function () { html: _.constant('formatted html'), }; - let f = new TestFormat(); - let text = f.getConverterFor('text'); - let html = f.getConverterFor('html'); + const f = new TestFormat(); + const text = f.getConverterFor('text'); + const html = f.getConverterFor('html'); expect(text).to.not.be(html); expect(text('formatted text')).to.be('formatted text'); expect(html('formatted html')).to.be('formatted html'); @@ -105,13 +105,13 @@ describe('FieldFormat class', function () { it('does not escape the output of the text converter', function () { TestFormat.prototype._convert = _.constant(''); - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'text')).to.contain('<'); }); it('does escape the output of the text converter if used in an html context', function () { TestFormat.prototype._convert = _.constant(''); - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'html')).to.not.contain('<'); }); @@ -121,7 +121,7 @@ describe('FieldFormat class', function () { html: _.constant(''), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'text')).to.be(''); expect(f.convert('', 'html')).to.be(''); }); @@ -134,7 +134,7 @@ describe('FieldFormat class', function () { html: _.constant('html'), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('val')).to.be('text'); }); @@ -144,12 +144,12 @@ describe('FieldFormat class', function () { html: _.constant('html'), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('val', 'html')).to.be('html'); }); it('formats a value as " - " when no value is specified', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert()).to.be(' - '); }); }); diff --git a/src/ui/public/index_patterns/__tests__/_index_pattern.js b/src/ui/public/index_patterns/__tests__/_index_pattern.js index 9503deeb9e446..fda66d2d3c7f1 100644 --- a/src/ui/public/index_patterns/__tests__/_index_pattern.js +++ b/src/ui/public/index_patterns/__tests__/_index_pattern.js @@ -21,7 +21,7 @@ describe('index pattern', function () { let DocSource; let config; let docSourceResponse; - let indexPatternId = 'test-pattern'; + const indexPatternId = 'test-pattern'; let indexPattern; let calculateIndices; let $rootScope; diff --git a/src/ui/public/index_patterns/__tests__/_map_field.js b/src/ui/public/index_patterns/__tests__/_map_field.js index 3384e9c530a7c..4832d85a354d6 100644 --- a/src/ui/public/index_patterns/__tests__/_map_field.js +++ b/src/ui/public/index_patterns/__tests__/_map_field.js @@ -18,25 +18,25 @@ describe('field mapping normalizer (mapField)', function () { }); it('should return a modified copy of the object, not modify the original', function () { - let pristine = _.cloneDeep(fields['foo.bar']); - let mapped = fn(fields['foo.bar'], 'foo.bar'); + const pristine = _.cloneDeep(fields['foo.bar']); + const mapped = fn(fields['foo.bar'], 'foo.bar'); expect(fields['foo.bar']).to.not.eql(mapped); expect(fields['foo.bar']).to.eql(pristine); }); it('should not consider _id indexed unless it is', function () { - let mapped = fn(fields._id, '_id'); + const mapped = fn(fields._id, '_id'); expect(mapped.indexed).to.be(false); - let mapping = _.cloneDeep(fields._id); + const mapping = _.cloneDeep(fields._id); mapping.mapping._id.index = 'not_analyzed'; - let mapped2 = fn(mapping, '_id'); + const mapped2 = fn(mapping, '_id'); expect(mapped2.indexed).to.be(true); }); it('should always consider _timestamp to be an indexed date', function () { - let mapped = fn(fields._timestamp, '_timestamp'); + const mapped = fn(fields._timestamp, '_timestamp'); expect(mapped.indexed).to.be(true); expect(mapped.type).to.be('date'); }); @@ -51,7 +51,7 @@ describe('field mapping normalizer (mapField)', function () { }); it('should treat other values for index as true', function () { - let mapped = fn(fields.not_analyzed_field, 'not_analyzed_field'); + const mapped = fn(fields.not_analyzed_field, 'not_analyzed_field'); expect(mapped.indexed).to.be(true); }); diff --git a/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js b/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js index e2313bce95759..39f688a74fa7a 100644 --- a/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js +++ b/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; describe('Index pattern to wildcard', function () { - let fn = require('ui/index_patterns/_pattern_to_wildcard')(); + const fn = require('ui/index_patterns/_pattern_to_wildcard')(); it('should be a function', function () { diff --git a/src/ui/public/index_patterns/__tests__/flatten_hit.js b/src/ui/public/index_patterns/__tests__/flatten_hit.js index 632e959b263cc..882d44fafa655 100644 --- a/src/ui/public/index_patterns/__tests__/flatten_hit.js +++ b/src/ui/public/index_patterns/__tests__/flatten_hit.js @@ -13,7 +13,7 @@ describe('IndexPattern#flattenHit()', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let indexPattern = { + const indexPattern = { fields: { byName: { 'message': { type: 'string' }, diff --git a/src/ui/public/index_patterns/__tests__/intervals.js b/src/ui/public/index_patterns/__tests__/intervals.js index ff486c86a68c4..78b8e082dd249 100644 --- a/src/ui/public/index_patterns/__tests__/intervals.js +++ b/src/ui/public/index_patterns/__tests__/intervals.js @@ -14,10 +14,10 @@ describe('Index Patterns', function () { })); it('should return correct indices for hourly [logstash-]YYYY.MM.DD.HH', function () { - let start = moment.utc('2014-01-01T07:00:00Z'); - let end = moment.utc('2014-01-01T08:30:00Z'); - let interval = { name: 'hours', startOf: 'hour', display: 'Hourly' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM.DD.HH', interval, start, end); + const start = moment.utc('2014-01-01T07:00:00Z'); + const end = moment.utc('2014-01-01T08:30:00Z'); + const interval = { name: 'hours', startOf: 'hour', display: 'Hourly' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM.DD.HH', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.01.01.07', @@ -33,10 +33,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for daily [logstash-]YYYY.MM.DD', function () { - let start = moment(1418244231248); - let end = moment(1418849261281); - let interval = { name: 'days', startOf: 'day', display: 'Daily' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM.DD', interval, start, end); + const start = moment(1418244231248); + const end = moment(1418849261281); + const interval = { name: 'days', startOf: 'day', display: 'Daily' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM.DD', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.12.10', @@ -82,10 +82,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for monthly [logstash-]YYYY.MM', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'months', startOf: 'month', display: 'Monthly' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM', interval, start, end); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'months', startOf: 'month', display: 'Monthly' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.12', @@ -106,10 +106,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for yearly [logstash-]YYYY', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014', @@ -126,10 +126,10 @@ describe('Index Patterns', function () { context('with sortDirection=asc', function () { it('returns values in ascending order', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'asc'); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'asc'); expect(list).to.eql([ { index: 'logstash-2014', @@ -147,10 +147,10 @@ describe('Index Patterns', function () { context('with sortDirection=desc', function () { it('returns values in descending order', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'desc'); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'desc'); expect(list).to.eql([ { index: 'logstash-2015', diff --git a/src/ui/public/index_patterns/_cast_mapping_type.js b/src/ui/public/index_patterns/_cast_mapping_type.js index bfeab98c2a171..93f36b18bffc1 100644 --- a/src/ui/public/index_patterns/_cast_mapping_type.js +++ b/src/ui/public/index_patterns/_cast_mapping_type.js @@ -36,7 +36,7 @@ export default function CastMappingTypeFn() { function castMappingType(name) { if (!name) return 'unknown'; - let match = castMappingType.types.byName[name]; + const match = castMappingType.types.byName[name]; return match ? match.type : 'string'; } diff --git a/src/ui/public/index_patterns/_ensure_some.js b/src/ui/public/index_patterns/_ensure_some.js index 8576b4fff4cd2..ffe6be42eed04 100644 --- a/src/ui/public/index_patterns/_ensure_some.js +++ b/src/ui/public/index_patterns/_ensure_some.js @@ -1,6 +1,6 @@ import errors from 'ui/errors'; export default function EnsureSomeIndexPatternsFn(Private, Notifier, $location, kbnUrl) { - let notify = new Notifier(); + const notify = new Notifier(); return function ensureSomeIndexPatterns() { return function promiseHandler(patterns) { diff --git a/src/ui/public/index_patterns/_field.js b/src/ui/public/index_patterns/_field.js index af4471f48feef..2edde66a1194b 100644 --- a/src/ui/public/index_patterns/_field.js +++ b/src/ui/public/index_patterns/_field.js @@ -3,10 +3,10 @@ import IndexPatternsFieldFormatFieldFormatProvider from 'ui/index_patterns/_fiel import IndexPatternsFieldTypesProvider from 'ui/index_patterns/_field_types'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope, Notifier) { - let notify = new Notifier({ location: 'IndexPattern Field' }); - let FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); - let fieldTypes = Private(IndexPatternsFieldTypesProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const notify = new Notifier({ location: 'IndexPattern Field' }); + const FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); + const fieldTypes = Private(IndexPatternsFieldTypesProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); function Field(indexPattern, spec) { // unwrap old instances of Field @@ -15,7 +15,7 @@ export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope // constuct this object using ObjDefine class, which // extends the Field.prototype but gets it's properties // defined using the logic below - let obj = new ObjDefine(spec, Field.prototype); + const obj = new ObjDefine(spec, Field.prototype); if (spec.name === '_source') { spec.type = '_source'; @@ -38,10 +38,10 @@ export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope format = indexPattern.fieldFormatMap[spec.name] || fieldFormats.getDefaultInstance(spec.type); } - let indexed = !!spec.indexed; - let scripted = !!spec.scripted; - let sortable = spec.name === '_score' || ((indexed || scripted) && type.sortable); - let filterable = spec.name === '_id' || scripted || (indexed && type.filterable); + const indexed = !!spec.indexed; + const scripted = !!spec.scripted; + const sortable = spec.name === '_score' || ((indexed || scripted) && type.sortable); + const filterable = spec.name === '_id' || scripted || (indexed && type.filterable); obj.fact('name'); obj.fact('type'); diff --git a/src/ui/public/index_patterns/_field_format/content_types.js b/src/ui/public/index_patterns/_field_format/content_types.js index ed82f0210c1f0..c19edabe35669 100644 --- a/src/ui/public/index_patterns/_field_format/content_types.js +++ b/src/ui/public/index_patterns/_field_format/content_types.js @@ -3,7 +3,7 @@ import angular from 'angular'; import 'ui/highlight'; export default function contentTypesProvider(highlightFilter) { - let types = { + const types = { html: function (format, convert) { return function recurse(value, field, hit) { if (value == null) { @@ -14,10 +14,10 @@ export default function contentTypesProvider(highlightFilter) { return convert.call(format, value, field, hit); } - let subVals = value.map(function (v) { + const subVals = value.map(function (v) { return recurse(v, field, hit); }); - let useMultiLine = subVals.some(function (sub) { + const useMultiLine = subVals.some(function (sub) { return sub.indexOf('\n') > -1; }); @@ -42,7 +42,7 @@ export default function contentTypesProvider(highlightFilter) { } function fallbackHtml(value, field, hit) { - let formatted = _.escape(this.convert(value, 'text')); + const formatted = _.escape(this.convert(value, 'text')); if (!hit || !hit.highlight || !hit.highlight[field.name]) { return formatted; @@ -52,8 +52,8 @@ export default function contentTypesProvider(highlightFilter) { } function setup(format) { - let src = format._convert || {}; - let converters = format._convert = {}; + const src = format._convert || {}; + const converters = format._convert = {}; converters.text = types.text(format, src.text || fallbackText); converters.html = types.html(format, src.html || fallbackHtml); diff --git a/src/ui/public/index_patterns/_field_format/field_format.js b/src/ui/public/index_patterns/_field_format/field_format.js index 53b48c69985bd..0084cea0477cd 100644 --- a/src/ui/public/index_patterns/_field_format/field_format.js +++ b/src/ui/public/index_patterns/_field_format/field_format.js @@ -1,10 +1,10 @@ import _ from 'lodash'; import IndexPatternsFieldFormatContentTypesProvider from 'ui/index_patterns/_field_format/content_types'; export default function FieldFormatClassProvider(config, $rootScope, Private) { - let contentTypes = Private(IndexPatternsFieldFormatContentTypesProvider); + const contentTypes = Private(IndexPatternsFieldFormatContentTypesProvider); function FieldFormat(params) { - let self = this; + const self = this; // give the constructor a more appropriate name self.type = self.constructor; @@ -59,7 +59,7 @@ export default function FieldFormatClassProvider(config, $rootScope, Private) { * @return {any} */ FieldFormat.prototype.param = function (name) { - let val = this._params[name]; + const val = this._params[name]; if (val || val === false || val === 0) { // truthy, false, or 0 are fine // '', NaN, null, undefined, etc are not @@ -84,8 +84,8 @@ export default function FieldFormatClassProvider(config, $rootScope, Private) { * @return {object} */ FieldFormat.prototype.toJSON = function () { - let type = this.type; - let defaults = this._paramDefaults; + const type = this.type; + const defaults = this._paramDefaults; let params = _.transform(this._params, function (uniqParams, val, param) { if (val !== defaults[param]) { diff --git a/src/ui/public/index_patterns/_field_list.js b/src/ui/public/index_patterns/_field_list.js index 438159f334de6..ddfc65ff042a5 100644 --- a/src/ui/public/index_patterns/_field_list.js +++ b/src/ui/public/index_patterns/_field_list.js @@ -2,7 +2,7 @@ import IndexedArray from 'ui/indexed_array'; import _ from 'lodash'; import IndexPatternsFieldProvider from 'ui/index_patterns/_field'; export default function FieldListProvider(Private) { - let Field = Private(IndexPatternsFieldProvider); + const Field = Private(IndexPatternsFieldProvider); _.class(FieldList).inherits(IndexedArray); function FieldList(indexPattern, specs) { diff --git a/src/ui/public/index_patterns/_flatten_hit.js b/src/ui/public/index_patterns/_flatten_hit.js index 7d137cfd070e6..c757789885138 100644 --- a/src/ui/public/index_patterns/_flatten_hit.js +++ b/src/ui/public/index_patterns/_flatten_hit.js @@ -9,10 +9,10 @@ export default function FlattenHitProvider(config) { }); function flattenHit(indexPattern, hit) { - let flat = {}; + const flat = {}; // recursively merge _source - let fields = indexPattern.fields.byName; + const fields = indexPattern.fields.byName; (function flatten(obj, keyPrefix) { keyPrefix = keyPrefix ? keyPrefix + '.' : ''; _.forOwn(obj, function (val, key) { @@ -20,8 +20,8 @@ export default function FlattenHitProvider(config) { if (flat[key] !== void 0) return; - let hasValidMapping = (fields[key] && fields[key].type !== 'conflict'); - let isValue = !_.isPlainObject(val); + const hasValidMapping = (fields[key] && fields[key].type !== 'conflict'); + const isValue = !_.isPlainObject(val); if (hasValidMapping || isValue) { flat[key] = val; diff --git a/src/ui/public/index_patterns/_format_hit.js b/src/ui/public/index_patterns/_format_hit.js index d188952f33532..6f705da8b77b4 100644 --- a/src/ui/public/index_patterns/_format_hit.js +++ b/src/ui/public/index_patterns/_format_hit.js @@ -5,7 +5,7 @@ import _ from 'lodash'; export default function (indexPattern, defaultFormat) { function convert(hit, val, fieldName) { - let field = indexPattern.fields.byName[fieldName]; + const field = indexPattern.fields.byName[fieldName]; if (!field) return defaultFormat.convert(val, 'html'); return field.format.getConverterFor('html')(val, field, hit); } @@ -15,12 +15,12 @@ export default function (indexPattern, defaultFormat) { // use and update the partial cache, but don't rewrite it. _source is stored in partials // but not $$_formatted - let partials = hit.$$_partialFormatted || (hit.$$_partialFormatted = {}); - let cache = hit.$$_formatted = {}; + const partials = hit.$$_partialFormatted || (hit.$$_partialFormatted = {}); + const cache = hit.$$_formatted = {}; _.forOwn(indexPattern.flattenHit(hit), function (val, fieldName) { // sync the formatted and partial cache - let formatted = partials[fieldName] == null ? convert(hit, val, fieldName) : partials[fieldName]; + const formatted = partials[fieldName] == null ? convert(hit, val, fieldName) : partials[fieldName]; cache[fieldName] = partials[fieldName] = formatted; }); @@ -37,7 +37,7 @@ export default function (indexPattern, defaultFormat) { partials = hit.$$_partialFormatted = {}; } - let val = fieldName === '_source' ? hit._source : indexPattern.flattenHit(hit)[fieldName]; + const val = fieldName === '_source' ? hit._source : indexPattern.flattenHit(hit)[fieldName]; return partials[fieldName] = convert(hit, val, fieldName); }; diff --git a/src/ui/public/index_patterns/_get_computed_fields.js b/src/ui/public/index_patterns/_get_computed_fields.js index 8730183a60066..e5bb687fded3c 100644 --- a/src/ui/public/index_patterns/_get_computed_fields.js +++ b/src/ui/public/index_patterns/_get_computed_fields.js @@ -2,8 +2,8 @@ import _ from 'lodash'; // Takes a hit, merges it with any stored/scripted fields, and with the metaFields // returns a flattened version export default function () { - let self = this; - let scriptFields = {}; + const self = this; + const scriptFields = {}; let docvalueFields = []; docvalueFields = _.pluck(self.fields.byType.date, 'name'); diff --git a/src/ui/public/index_patterns/_get_ids.js b/src/ui/public/index_patterns/_get_ids.js index b499b1dd3859d..969e186a4fb4e 100644 --- a/src/ui/public/index_patterns/_get_ids.js +++ b/src/ui/public/index_patterns/_get_ids.js @@ -5,7 +5,7 @@ export default function GetIndexPatternIdsFn(es, kbnIndex) { // didn't incorportate with the indexPattern cache to prevent id collisions. let cachedPromise; - let getIds = function () { + const getIds = function () { if (cachedPromise) { // retrun a clone of the cached response return cachedPromise.then(function (cachedResp) { diff --git a/src/ui/public/index_patterns/_intervals.js b/src/ui/public/index_patterns/_intervals.js index 89617306db719..8fe028348be19 100644 --- a/src/ui/public/index_patterns/_intervals.js +++ b/src/ui/public/index_patterns/_intervals.js @@ -3,7 +3,7 @@ import moment from 'moment'; import IndexedArray from 'ui/indexed_array'; export default function IndexNameIntervalsService(timefilter) { - let intervals = new IndexedArray({ + const intervals = new IndexedArray({ index: ['name'], initialSet: [ { @@ -40,10 +40,10 @@ export default function IndexNameIntervalsService(timefilter) { // setup the range that the list will span, return two moment objects that // are in proper order. a and b can be numbers to specify to go before or after now (respectively) // a certain number of times, based on the interval - let range = [[a, 'min', 'startOf'], [b, 'max', 'startOf']].map(function (v) { + const range = [[a, 'min', 'startOf'], [b, 'max', 'startOf']].map(function (v) { let val = v[0]; - let bound = v[1]; - let extend = v[2]; + const bound = v[1]; + const extend = v[2]; // grab a bound from the time filter if (val == null) { @@ -64,12 +64,12 @@ export default function IndexNameIntervalsService(timefilter) { if (!interval) throw new Error('Interval must be one of ' + _.pluck(intervals, 'name')); } - let indexList = []; + const indexList = []; let start = range.shift(); // turn stop into milliseconds to that it's not constantly converted by the while condition - let stop = range.shift().valueOf(); + const stop = range.shift().valueOf(); - let add = sortDirection === 'desc' ? 'unshift' : 'push'; + const add = sortDirection === 'desc' ? 'unshift' : 'push'; while (start <= stop) { const index = start.format(format); diff --git a/src/ui/public/index_patterns/_local_cache.js b/src/ui/public/index_patterns/_local_cache.js index 64ec26847600a..52a7079f581b2 100644 --- a/src/ui/public/index_patterns/_local_cache.js +++ b/src/ui/public/index_patterns/_local_cache.js @@ -4,17 +4,17 @@ import angular from 'angular'; export default function LocalCacheFactory() { function LocalCache(opts) { opts = opts || {}; - let _id = opts.id || function (o) { return '' + o; }; + const _id = opts.id || function (o) { return '' + o; }; let _cache = {}; this.get = function (obj) { - let id = _id(obj); + const id = _id(obj); return _cache[id] ? JSON.parse(_cache[id]) : null; }; this.set = function (obj, val) { - let id = _id(obj); - let clean = !_cache.hasOwnProperty(id); + const id = _id(obj); + const clean = !_cache.hasOwnProperty(id); _cache[id] = angular.toJson(val); return clean; }; @@ -25,7 +25,7 @@ export default function LocalCacheFactory() { return; } - let id = _id(obj); + const id = _id(obj); delete _cache[id]; }; } diff --git a/src/ui/public/index_patterns/_map_field.js b/src/ui/public/index_patterns/_map_field.js index b4d3a4aa42f78..08a8ca55c10cc 100644 --- a/src/ui/public/index_patterns/_map_field.js +++ b/src/ui/public/index_patterns/_map_field.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexPatternsCastMappingTypeProvider from 'ui/index_patterns/_cast_mapping_type'; export default function MapFieldFn(Private, config) { - let castMappingType = Private(IndexPatternsCastMappingTypeProvider); + const castMappingType = Private(IndexPatternsCastMappingTypeProvider); /** * Accepts a field object and its name, and tries to give it a mapping @@ -10,11 +10,11 @@ export default function MapFieldFn(Private, config) { * @return {Object} - the resulting field after overrides and tweaking */ return function mapField(field, name) { - let keys = Object.keys(field.mapping); + const keys = Object.keys(field.mapping); if (keys.length === 0 || (name[0] === '_') && !_.contains(config.get('metaFields'), name)) return; // Override the mapping, even if elasticsearch says otherwise - let mappingOverrides = { + const mappingOverrides = { _source: { type: '_source' }, _index: { type: 'string' }, _type: { type: 'string' }, @@ -29,7 +29,7 @@ export default function MapFieldFn(Private, config) { } }; - let mapping = _.cloneDeep(field.mapping[keys.shift()]); + const mapping = _.cloneDeep(field.mapping[keys.shift()]); if (!mapping.index || mapping.index === 'no') { // elasticsearch responds with false sometimes and 'no' others diff --git a/src/ui/public/index_patterns/_mapper.js b/src/ui/public/index_patterns/_mapper.js index 0ee8984327749..983f86e7a716d 100644 --- a/src/ui/public/index_patterns/_mapper.js +++ b/src/ui/public/index_patterns/_mapper.js @@ -7,19 +7,19 @@ import IndexPatternsPatternToWildcardProvider from 'ui/index_patterns/_pattern_t import IndexPatternsLocalCacheProvider from 'ui/index_patterns/_local_cache'; export default function MapperService(Private, Promise, es, config, kbnIndex) { - let transformMappingIntoFields = Private(IndexPatternsTransformMappingIntoFieldsProvider); - let intervals = Private(IndexPatternsIntervalsProvider); - let patternToWildcard = Private(IndexPatternsPatternToWildcardProvider); + const transformMappingIntoFields = Private(IndexPatternsTransformMappingIntoFieldsProvider); + const intervals = Private(IndexPatternsIntervalsProvider); + const patternToWildcard = Private(IndexPatternsPatternToWildcardProvider); - let LocalCache = Private(IndexPatternsLocalCacheProvider); + const LocalCache = Private(IndexPatternsLocalCacheProvider); function Mapper() { // Save a reference to mapper - let self = this; + const self = this; // proper-ish cache, keeps a clean copy of the object, only returns copies of it's copy - let fieldCache = self.cache = new LocalCache(); + const fieldCache = self.cache = new LocalCache(); /** * Gets an object containing all fields with their mappings @@ -29,9 +29,9 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { * @async */ self.getFieldsForIndexPattern = function (indexPattern, skipIndexPatternCache) { - let id = indexPattern.id; + const id = indexPattern.id; - let cache = fieldCache.get(id); + const cache = fieldCache.get(id); if (cache) return Promise.resolve(cache); if (!skipIndexPatternCache) { @@ -81,7 +81,7 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { }) .then(function (resp) { // let all = Object.keys(resp).sort(); - let all = _(resp) + const all = _(resp) .map(function (index, key) { if (index.aliases) { return [Object.keys(index.aliases), key]; @@ -94,8 +94,8 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { .uniq(true) .value(); - let matches = all.filter(function (existingIndex) { - let parsed = moment(existingIndex, indexPattern.id); + const matches = all.filter(function (existingIndex) { + const parsed = moment(existingIndex, indexPattern.id); return existingIndex === parsed.format(indexPattern.id); }); diff --git a/src/ui/public/index_patterns/_pattern_cache.js b/src/ui/public/index_patterns/_pattern_cache.js index e9f57f5188e0a..7062ddb44bfd4 100644 --- a/src/ui/public/index_patterns/_pattern_cache.js +++ b/src/ui/public/index_patterns/_pattern_cache.js @@ -1,9 +1,9 @@ import _ from 'lodash'; export default function PatternCache() { - let vals = {}; + const vals = {}; - let validId = function (id) { + const validId = function (id) { return typeof id !== 'object'; }; diff --git a/src/ui/public/index_patterns/_pattern_to_wildcard.js b/src/ui/public/index_patterns/_pattern_to_wildcard.js index 447af376c807d..0193241ac12ca 100644 --- a/src/ui/public/index_patterns/_pattern_to_wildcard.js +++ b/src/ui/public/index_patterns/_pattern_to_wildcard.js @@ -5,7 +5,7 @@ export default function PatternToWildcardFn() { let inPattern = false; for (let i = 0; i < format.length; i++) { - let ch = format.charAt(i); + const ch = format.charAt(i); switch (ch) { case '[': inPattern = false; diff --git a/src/ui/public/index_patterns/_transform_mapping_into_fields.js b/src/ui/public/index_patterns/_transform_mapping_into_fields.js index 059101e76695e..cf9c3d102facb 100644 --- a/src/ui/public/index_patterns/_transform_mapping_into_fields.js +++ b/src/ui/public/index_patterns/_transform_mapping_into_fields.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexPatternsMapFieldProvider from 'ui/index_patterns/_map_field'; export default function transformMappingIntoFields(Private, kbnIndex, config) { - let mapField = Private(IndexPatternsMapFieldProvider); + const mapField = Private(IndexPatternsMapFieldProvider); /** @@ -14,15 +14,15 @@ export default function transformMappingIntoFields(Private, kbnIndex, config) { * use-cases */ return function (response) { - let fields = {}; + const fields = {}; _.each(response, function (index, indexName) { if (indexName === kbnIndex) return; _.each(index.mappings, function (mappings) { _.each(mappings, function (field, name) { - let keys = Object.keys(field.mapping); + const keys = Object.keys(field.mapping); if (keys.length === 0 || (name[0] === '_') && !_.contains(config.get('metaFields'), name)) return; - let mapping = mapField(field, name); + const mapping = mapField(field, name); if (fields[name]) { if (fields[name].type !== mapping.type) { @@ -39,7 +39,7 @@ export default function transformMappingIntoFields(Private, kbnIndex, config) { config.get('metaFields').forEach(function (meta) { if (fields[meta]) return; - let field = { mapping: {} }; + const field = { mapping: {} }; field.mapping[meta] = {}; fields[meta] = mapField(field, meta); }); diff --git a/src/ui/public/index_patterns/index_patterns.js b/src/ui/public/index_patterns/index_patterns.js index 18ea1b7c95cfd..0a366fb8c2e07 100644 --- a/src/ui/public/index_patterns/index_patterns.js +++ b/src/ui/public/index_patterns/index_patterns.js @@ -9,20 +9,20 @@ import IndexPatternsMapperProvider from 'ui/index_patterns/_mapper'; import IndexPatternsPatternToWildcardProvider from 'ui/index_patterns/_pattern_to_wildcard'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana/index_patterns'); +const module = uiModules.get('kibana/index_patterns'); function IndexPatternsProvider(es, Notifier, Private, Promise, kbnIndex) { - let self = this; + const self = this; - let IndexPattern = Private(IndexPatternsIndexPatternProvider); - let patternCache = Private(IndexPatternsPatternCacheProvider); + const IndexPattern = Private(IndexPatternsIndexPatternProvider); + const patternCache = Private(IndexPatternsPatternCacheProvider); - let notify = new Notifier({ location: 'IndexPatterns Service'}); + const notify = new Notifier({ location: 'IndexPatterns Service'}); self.get = function (id) { if (!id) return self.make(); - let cache = patternCache.get(id); + const cache = patternCache.get(id); return cache || patternCache.set(id, self.make(id)); }; diff --git a/src/ui/public/index_patterns/route_setup/load_default.js b/src/ui/public/index_patterns/route_setup/load_default.js index 270e163c06c92..d59b1efb498cd 100644 --- a/src/ui/public/index_patterns/route_setup/load_default.js +++ b/src/ui/public/index_patterns/route_setup/load_default.js @@ -4,26 +4,26 @@ import { NoDefaultIndexPattern, NoDefinedIndexPatterns } from 'ui/errors'; import GetIdsProvider from '../_get_ids'; import CourierDataSourceRootSearchSourceProvider from 'ui/courier/data_source/_root_search_source'; import uiRoutes from 'ui/routes'; -let notify = new Notifier({ +const notify = new Notifier({ location: 'Index Patterns' }); module.exports = function (opts) { opts = opts || {}; - let whenMissingRedirectTo = opts.whenMissingRedirectTo || null; + const whenMissingRedirectTo = opts.whenMissingRedirectTo || null; let defaultRequiredToasts = null; uiRoutes .addSetupWork(function loadDefaultIndexPattern(Private, Promise, $route, config, indexPatterns) { - let getIds = Private(GetIdsProvider); - let rootSearchSource = Private(CourierDataSourceRootSearchSourceProvider); - let route = _.get($route, 'current.$$route'); + const getIds = Private(GetIdsProvider); + const rootSearchSource = Private(CourierDataSourceRootSearchSourceProvider); + const route = _.get($route, 'current.$$route'); return getIds() .then(function (patterns) { let defaultId = config.get('defaultIndex'); let defined = !!defaultId; - let exists = _.contains(patterns, defaultId); + const exists = _.contains(patterns, defaultId); if (defined && !exists) { config.remove('defaultIndex'); @@ -48,7 +48,7 @@ module.exports = function (opts) { // failure function (err, kbnUrl) { - let hasDefault = !(err instanceof NoDefaultIndexPattern); + const hasDefault = !(err instanceof NoDefaultIndexPattern); if (hasDefault || !whenMissingRedirectTo) throw err; // rethrow kbnUrl.change(whenMissingRedirectTo); diff --git a/src/ui/public/indexed_array/__tests__/indexed_array.js b/src/ui/public/indexed_array/__tests__/indexed_array.js index 69820fbe8bba4..040bc29046a06 100644 --- a/src/ui/public/indexed_array/__tests__/indexed_array.js +++ b/src/ui/public/indexed_array/__tests__/indexed_array.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; import IndexedArray from 'ui/indexed_array'; // this is generally a data-structure that IndexedArray is good for managing -let users = [ +const users = [ { name: 'John', id: 69, username: 'beast', group: 'admins' }, { name: 'Anon', id: 0, username: 'shhhh', group: 'secret' }, { name: 'Fern', id: 42, username: 'kitty', group: 'editor' }, @@ -43,7 +43,7 @@ describe('IndexedArray', function () { describe('Indexing', function () { it('provides the initial set', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ initialSet: [1, 2, 3] }); @@ -55,7 +55,7 @@ describe('IndexedArray', function () { }); it('indexes the initial set', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ index: ['username'], initialSet: users }); @@ -66,11 +66,11 @@ describe('IndexedArray', function () { it('updates indices after values are added', function () { // split up the user list, and add it in chunks - let firstUser = users.slice(0, 1).pop(); - let otherUsers = users.slice(1); + const firstUser = users.slice(0, 1).pop(); + const otherUsers = users.slice(1); // start off with all but the first - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: otherUsers @@ -86,7 +86,7 @@ describe('IndexedArray', function () { it('updates indices after values are removed', function () { // start off with all - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: users @@ -95,18 +95,18 @@ describe('IndexedArray', function () { // remove the last reg.pop(); - let expectedCount = users.length - 1; + const expectedCount = users.length - 1; // indexed lists should be updated expect(reg).to.have.length(expectedCount); - let sumOfGroups = _.reduce(reg.byGroup, function (note, group) { + const sumOfGroups = _.reduce(reg.byGroup, function (note, group) { return note + group.length; }, 0); expect(sumOfGroups).to.eql(expectedCount); }); it('removes items based on a predicate', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: users @@ -120,7 +120,7 @@ describe('IndexedArray', function () { }); it('updates indices after values are re-ordered', function () { - let rawUsers = users.slice(0); + const rawUsers = users.slice(0); // collect and shuffle the ids available let ids = []; @@ -128,18 +128,18 @@ describe('IndexedArray', function () { ids = _.shuffle(ids); // move something here - let toI = ids.shift(); + const toI = ids.shift(); // from here - let fromI = ids.shift(); + const fromI = ids.shift(); // do the move - let move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; + const move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; - let reg = new IndexedArray({ + const reg = new IndexedArray({ index: ['username'], initialSet: rawUsers }); - let index = reg.byUsername; + const index = reg.byUsername; move(reg); diff --git a/src/ui/public/indexed_array/__tests__/inflector.js b/src/ui/public/indexed_array/__tests__/inflector.js index 3fc45e1a9f974..e7628ecf159fc 100644 --- a/src/ui/public/indexed_array/__tests__/inflector.js +++ b/src/ui/public/indexed_array/__tests__/inflector.js @@ -3,13 +3,13 @@ import expect from 'expect.js'; describe('IndexedArray Inflector', function () { it('returns a function', function () { - let getter = inflector(); + const getter = inflector(); expect(getter).to.be.a('function'); }); describe('fn', function () { it('prepends a prefix', function () { - let inflect = inflector('my'); + const inflect = inflector('my'); expect(inflect('Family')).to.be('myFamily'); expect(inflect('family')).to.be('myFamily'); @@ -17,7 +17,7 @@ describe('IndexedArray Inflector', function () { }); it('adds both a prefix and suffix', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('box')).to.be('fooBoxBar'); expect(inflect('box.car.MAX')).to.be('fooBoxCarMaxBar'); @@ -25,19 +25,19 @@ describe('IndexedArray Inflector', function () { }); it('ignores prefix if it is already at the end of the inflected string', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('fooBox')).to.be('fooBoxBar'); expect(inflect('FooBox')).to.be('FooBoxBar'); }); it('ignores postfix if it is already at the end of the inflected string', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('bar')).to.be('fooBar'); expect(inflect('showBoxBar')).to.be('fooShowBoxBar'); }); it('works with "name"', function () { - let inflect = inflector('in', 'Order'); + const inflect = inflector('in', 'Order'); expect(inflect('name')).to.be('inNameOrder'); }); }); diff --git a/src/ui/public/indexed_array/indexed_array.js b/src/ui/public/indexed_array/indexed_array.js index 3c7f81fcb52db..3f3325e2d3f7b 100644 --- a/src/ui/public/indexed_array/indexed_array.js +++ b/src/ui/public/indexed_array/indexed_array.js @@ -2,12 +2,12 @@ import _ from 'lodash'; import inflector from 'ui/indexed_array/inflector'; -let pathGetter = _(_.get).rearg(1, 0).ary(2); -let inflectIndex = inflector('by'); -let inflectOrder = inflector('in', 'Order'); +const pathGetter = _(_.get).rearg(1, 0).ary(2); +const inflectIndex = inflector('by'); +const inflectOrder = inflector('in', 'Order'); -let CLEAR_CACHE = {}; -let OPT_NAMES = IndexedArray.OPT_NAMES = ['index', 'group', 'order', 'initialSet', 'immutable']; +const CLEAR_CACHE = {}; +const OPT_NAMES = IndexedArray.OPT_NAMES = ['index', 'group', 'order', 'initialSet', 'immutable']; /** * Generic extension of Array class, which will index (and reindex) the @@ -69,11 +69,11 @@ IndexedArray.prototype._setupIndices = function (props, inflect, op) { // shortcut for empty props if (!props || props.length === 0) return; - let self = this; + const self = this; return props.map(function (prop) { - let from = pathGetter.partial(prop).value(); - let to = inflect(prop); + const from = pathGetter.partial(prop).value(); + const to = inflect(prop); let cache; Object.defineProperty(self, to, { @@ -105,7 +105,7 @@ IndexedArray.prototype._setupIndices = function (props, inflect, op) { * @return {undefined} */ IndexedArray.prototype._clearIndices = function () { - let self = this; + const self = this; self._indexNames.forEach(function (name) { self[name] = CLEAR_CACHE; }); @@ -120,7 +120,7 @@ IndexedArray.prototype._clearIndices = function () { * @return {[type]} [description] */ 'pop push shift splice unshift reverse'.split(' ').forEach(function (method) { - let orig = Array.prototype[method]; + const orig = Array.prototype[method]; IndexedArray.prototype[method] = function (/* args... */) { // call the original method with this context @@ -141,7 +141,7 @@ IndexedArray.prototype._clearIndices = function () { * @return {array} - the removed data */ IndexedArray.prototype.remove = function (predicate, context) { - let out = _.remove(this, predicate, context); + const out = _.remove(this, predicate, context); _.remove(this.raw, predicate, context); this._clearIndices(); return out; diff --git a/src/ui/public/indexed_array/inflector.js b/src/ui/public/indexed_array/inflector.js index f879cbdf8965e..e2ef5eca31cda 100644 --- a/src/ui/public/indexed_array/inflector.js +++ b/src/ui/public/indexed_array/inflector.js @@ -8,7 +8,7 @@ function startsWith(str, test) { } function endsWith(str, test) { - let tooShort = str.length < test.length; + const tooShort = str.length < test.length; if (tooShort) return; return str.substr(str.length - test.length).toLowerCase() === test.toLowerCase(); diff --git a/src/ui/public/jquery/__tests__/find_test_subject.js b/src/ui/public/jquery/__tests__/find_test_subject.js index 7a70ec05bd2a1..8302712e78f68 100644 --- a/src/ui/public/jquery/__tests__/find_test_subject.js +++ b/src/ui/public/jquery/__tests__/find_test_subject.js @@ -7,42 +7,42 @@ function $make(subject) { describe('jQuery.findTestSubject', function () { it('finds all of the element with a subject', function () { - let $container = $('
'); - let $match = $make('subject').appendTo($container); - let $noMatch = $make('notSubject').appendTo($container); + const $container = $('
'); + const $match = $make('subject').appendTo($container); + const $noMatch = $make('notSubject').appendTo($container); - let $found = $container.findTestSubject('subject'); + const $found = $container.findTestSubject('subject'); expect($found.is($match)).to.be(true); expect($found.is($noMatch)).to.be(false); }); it('finds multiple elements with a subject', function () { - let $container = $('
'); - let $match = $make('subject').appendTo($container); - let $otherMatch = $make('subject').appendTo($container); + const $container = $('
'); + const $match = $make('subject').appendTo($container); + const $otherMatch = $make('subject').appendTo($container); - let $found = $container.findTestSubject('subject'); + const $found = $container.findTestSubject('subject'); expect($found.filter($match).size()).to.be(1); expect($found.filter($otherMatch).size()).to.be(1); }); it('finds all of the elements with either subject', function () { - let $container = $('
'); - let $match1 = $make('subject').appendTo($container); - let $match2 = $make('alsoSubject').appendTo($container); - let $noMatch = $make('notSubject').appendTo($container); + const $container = $('
'); + const $match1 = $make('subject').appendTo($container); + const $match2 = $make('alsoSubject').appendTo($container); + const $noMatch = $make('notSubject').appendTo($container); - let $found = $container.findTestSubject('subject', 'alsoSubject'); + const $found = $container.findTestSubject('subject', 'alsoSubject'); expect($found.filter($match1).size()).to.be(1); expect($found.filter($match2).size()).to.be(1); expect($found.filter($noMatch).size()).to.be(0); }); it('finds all of the elements with a decendant selector', function () { - let $container = $('
'); - let $parent = $make('foo name').appendTo($container); - let $bar = $make('bar othername').appendTo($parent); - let $baz = $make('baz third name').appendTo($parent); + const $container = $('
'); + const $parent = $make('foo name').appendTo($container); + const $bar = $make('bar othername').appendTo($parent); + const $baz = $make('baz third name').appendTo($parent); expect($container.findTestSubject('foo bar').is($bar)).to.be(true); expect($container.findTestSubject('foo bar').is($baz)).to.be(false); @@ -52,9 +52,9 @@ describe('jQuery.findTestSubject', function () { }); it('finds elements with compound subjects', function () { - let $container = $('
'); - let $bar = $make('button bar').appendTo($container); - let $baz = $make('button baz').appendTo($container); + const $container = $('
'); + const $bar = $make('button bar').appendTo($container); + const $baz = $make('button baz').appendTo($container); expect($container.findTestSubject('button&bar').is($bar)).to.be(true); expect($container.findTestSubject('button& bar').is($bar)).to.be(true); diff --git a/src/ui/public/jquery/find_test_subject.js b/src/ui/public/jquery/find_test_subject.js index 935bb67a14558..ecb85ea5944c9 100644 --- a/src/ui/public/jquery/find_test_subject.js +++ b/src/ui/public/jquery/find_test_subject.js @@ -45,7 +45,7 @@ module.exports = function bindToJquery($) { function findTestSubject(...subjectSelectors) { let $els = $(); - let $context = this; + const $context = this; subjectSelectors.forEach(function (selector) { $els = $els.add($context.find(testSubjSelector(selector))); diff --git a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js index bdb9759052e0d..e6fba1fbac2e4 100644 --- a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js +++ b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js @@ -303,7 +303,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(4); // check that the items were added - let matches = controller.menuItems.reduce((acc, item) => { + const matches = controller.menuItems.reduce((acc, item) => { if (item.key === 'green' || item.key === 'red') { acc[item.key] = item; } @@ -324,7 +324,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(3); // check that the items were added - let match = controller.menuItems.filter((item) => { + const match = controller.menuItems.filter((item) => { return item.key === 'green'; }); expect(match[0]).to.have.property('run'); diff --git a/src/ui/public/listen/__tests__/listen.js b/src/ui/public/listen/__tests__/listen.js index a4dcae53d176d..5c0384291f4e9 100644 --- a/src/ui/public/listen/__tests__/listen.js +++ b/src/ui/public/listen/__tests__/listen.js @@ -22,8 +22,8 @@ describe('listen component', function () { }); it('binds to an event emitter', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); function handler() {} $scope.$listen(emitter, 'hello', handler); @@ -33,8 +33,8 @@ describe('listen component', function () { }); it('binds to $scope, waiting for the destroy event', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); sinon.stub($scope, '$on'); sinon.stub($rootScope, '$on'); @@ -45,14 +45,14 @@ describe('listen component', function () { expect($rootScope.$on).to.have.property('callCount', 0); expect($scope.$on).to.have.property('callCount', 1); - let call = $scope.$on.firstCall; + const call = $scope.$on.firstCall; expect(call.args[0]).to.be('$destroy'); expect(call.args[1]).to.be.a('function'); }); it('unbinds the event handler when $destroy is triggered', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); sinon.stub($scope, '$on'); sinon.stub(emitter, 'off'); @@ -62,7 +62,7 @@ describe('listen component', function () { $scope.$listen(emitter, 'hello', handler); // get the unbinder that was registered to $scope - let unbinder = $scope.$on.firstCall.args[1]; + const unbinder = $scope.$on.firstCall.args[1]; // call the unbinder expect(emitter.off).to.have.property('callCount', 0); @@ -70,7 +70,7 @@ describe('listen component', function () { expect(emitter.off).to.have.property('callCount', 1); // check that the off args were as expected - let call = emitter.off.firstCall; + const call = emitter.off.firstCall; expect(call.args[0]).to.be('hello'); expect(call.args[1]).to.be(handler); }); diff --git a/src/ui/public/notify/__tests__/lib/_format_es_msg.js b/src/ui/public/notify/__tests__/lib/_format_es_msg.js index 5b89a909386bc..0fd73df79edc1 100644 --- a/src/ui/public/notify/__tests__/lib/_format_es_msg.js +++ b/src/ui/public/notify/__tests__/lib/_format_es_msg.js @@ -3,23 +3,23 @@ import expect from 'expect.js'; describe('formatESMsg', function () { it('should return undefined if passed a basic error', function () { - let err = new Error('This is a normal error'); + const err = new Error('This is a normal error'); - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.be(undefined); }); it('should return undefined if passed a string', function () { - let err = 'This is a error string'; + const err = 'This is a error string'; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.be(undefined); }); it('should return the root_cause if passed an extended elasticsearch', function () { - let err = new Error('This is an elasticsearch error'); + const err = new Error('This is an elasticsearch error'); err.resp = { error : { root_cause : [ @@ -30,13 +30,13 @@ describe('formatESMsg', function () { } }; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.equal('I am the detailed message'); }); it('should combine the reason messages if more than one is returned.', function () { - let err = new Error('This is an elasticsearch error'); + const err = new Error('This is an elasticsearch error'); err.resp = { error : { root_cause : [ @@ -50,7 +50,7 @@ describe('formatESMsg', function () { } }; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.equal('I am the detailed message 1\nI am the detailed message 2'); }); diff --git a/src/ui/public/notify/__tests__/lib/_format_msg.js b/src/ui/public/notify/__tests__/lib/_format_msg.js index 725fd6a518d73..a58f2fa4e2d72 100644 --- a/src/ui/public/notify/__tests__/lib/_format_msg.js +++ b/src/ui/public/notify/__tests__/lib/_format_msg.js @@ -3,26 +3,26 @@ import expect from 'expect.js'; describe('formatMsg', function () { it('should prepend the second argument to result', function () { - let actual = formatMsg('error message', 'unit_test'); + const actual = formatMsg('error message', 'unit_test'); expect(actual).to.equal('unit_test: error message'); }); it('should handle a simple string', function () { - let actual = formatMsg('error message'); + const actual = formatMsg('error message'); expect(actual).to.equal('error message'); }); it('should handle a simple Error object', function () { - let err = new Error('error message'); - let actual = formatMsg(err); + const err = new Error('error message'); + const actual = formatMsg(err); expect(actual).to.equal('error message'); }); it('should handle a simple Angular $http error object', function () { - let err = { + const err = { data: { statusCode: 403, error: 'Forbidden', @@ -32,13 +32,13 @@ describe('formatMsg', function () { config: {}, statusText: 'Forbidden' }; - let actual = formatMsg(err); + const actual = formatMsg(err); expect(actual).to.equal('Error 403 Forbidden: [security_exception] action [indices:data/read/mget] is unauthorized for user [user]'); }); it('should handle an extended elasticsearch error', function () { - let err = { + const err = { resp : { error : { root_cause : [ @@ -50,7 +50,7 @@ describe('formatMsg', function () { } }; - let actual = formatMsg(err); + const actual = formatMsg(err); expect(actual).to.equal('I am the detailed message'); }); diff --git a/src/ui/public/notify/__tests__/notifier.js b/src/ui/public/notify/__tests__/notifier.js index 7fea469a37875..57902227cc6a2 100644 --- a/src/ui/public/notify/__tests__/notifier.js +++ b/src/ui/public/notify/__tests__/notifier.js @@ -67,7 +67,7 @@ describe('Notifier', function () { }); it('sets timeRemaining and decrements', function () { - let notif = notify('error'); + const notif = notify('error'); expect(notif.timeRemaining).to.equal(300); $interval.flush(1000); @@ -75,8 +75,8 @@ describe('Notifier', function () { }); it('closes notification on lifetime expiry', function () { - let expectation = sinon.mock(); - let notif = notifier.error(message, expectation); + const expectation = sinon.mock(); + const notif = notifier.error(message, expectation); expectation.once(); expectation.withExactArgs('ignore'); @@ -87,7 +87,7 @@ describe('Notifier', function () { }); it('allows canceling of timer', function () { - let notif = notify('error'); + const notif = notify('error'); expect(notif.timerId).to.not.be(undefined); notif.cancelTimer(); @@ -96,7 +96,7 @@ describe('Notifier', function () { }); it('resets timer on addition to stack', function () { - let notif = notify('error'); + const notif = notify('error'); $interval.flush(100000); expect(notif.timeRemaining).to.equal(200); @@ -106,12 +106,12 @@ describe('Notifier', function () { }); it('allows reporting', function () { - let includesReport = _.includes(notify('error').actions, 'report'); + const includesReport = _.includes(notify('error').actions, 'report'); expect(includesReport).to.true; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('error').actions, 'accept'); + const includesAccept = _.includes(notify('error').actions, 'accept'); expect(includesAccept).to.true; }); @@ -144,12 +144,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('warning').actions, 'report'); + const includesReport = _.includes(notify('warning').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('warning').actions, 'accept'); + const includesAccept = _.includes(notify('warning').actions, 'accept'); expect(includesAccept).to.true; }); @@ -182,12 +182,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('info').actions, 'report'); + const includesReport = _.includes(notify('info').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('info').actions, 'accept'); + const includesAccept = _.includes(notify('info').actions, 'accept'); expect(includesAccept).to.true; }); @@ -345,12 +345,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('banner').actions, 'report'); + const includesReport = _.includes(notify('banner').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('banner').actions, 'accept'); + const includesAccept = _.includes(notify('banner').actions, 'accept'); expect(includesAccept).to.true; }); @@ -371,13 +371,13 @@ describe('Notifier', function () { function testVersionInfo(fnName) { context('when version is configured', function () { it('adds version to notification', function () { - let notification = notify(fnName); + const notification = notify(fnName); expect(notification.info.version).to.equal(version); }); }); context('when build number is configured', function () { it('adds buildNum to notification', function () { - let notification = notify(fnName); + const notification = notify(fnName); expect(notification.info.buildNum).to.equal(buildNum); }); }); diff --git a/src/ui/public/notify/directives.js b/src/ui/public/notify/directives.js index cb91b664d5403..bbef11f7e2bfe 100644 --- a/src/ui/public/notify/directives.js +++ b/src/ui/public/notify/directives.js @@ -5,7 +5,7 @@ import 'ui/notify/notify.less'; import 'ui/filters/markdown'; import 'ui/directives/truncated'; -let notify = uiModules.get('kibana/notify'); +const notify = uiModules.get('kibana/notify'); notify.directive('kbnNotifications', function () { return { diff --git a/src/ui/public/notify/errors.js b/src/ui/public/notify/errors.js index 68a040466124f..85f4ed66c7d47 100644 --- a/src/ui/public/notify/errors.js +++ b/src/ui/public/notify/errors.js @@ -1,8 +1,8 @@ import _ from 'lodash'; -let errors = {}; +const errors = {}; -let canStack = (function () { - let err = new Error(); +const canStack = (function () { + const err = new Error(); return !!err.stack; }()); diff --git a/src/ui/public/notify/lib/_format_es_msg.js b/src/ui/public/notify/lib/_format_es_msg.js index ac8c6b043a625..d812a04ec6eed 100644 --- a/src/ui/public/notify/lib/_format_es_msg.js +++ b/src/ui/public/notify/lib/_format_es_msg.js @@ -6,11 +6,11 @@ import _ from 'lodash'; * @returns {string} */ export default function formatESMsg(err) { - let rootCause = _.get(err, 'resp.error.root_cause'); + const rootCause = _.get(err, 'resp.error.root_cause'); if (!rootCause) { return; //undefined } - let result = _.pluck(rootCause, 'reason').join('\n'); + const result = _.pluck(rootCause, 'reason').join('\n'); return result; }; diff --git a/src/ui/public/notify/lib/_format_msg.js b/src/ui/public/notify/lib/_format_msg.js index 448c4fa4b2c8c..c77b550b5d20a 100644 --- a/src/ui/public/notify/lib/_format_msg.js +++ b/src/ui/public/notify/lib/_format_msg.js @@ -1,6 +1,6 @@ import _ from 'lodash'; import formatESMsg from 'ui/notify/lib/_format_es_msg'; -let has = _.has; +const has = _.has; /** * Formats the error message from an error object, extended elasticsearch @@ -15,7 +15,7 @@ function formatMsg(err, from) { rtn += from + ': '; } - let esMsg = formatESMsg(err); + const esMsg = formatESMsg(err); if (typeof err === 'string') { rtn += err; diff --git a/src/ui/public/notify/notifier.js b/src/ui/public/notify/notifier.js index 2113ede5c288e..4352a0d333cf2 100644 --- a/src/ui/public/notify/notifier.js +++ b/src/ui/public/notify/notifier.js @@ -7,17 +7,17 @@ import fatalSplashScreen from 'ui/notify/partials/fatal_splash_screen.html'; import 'ui/render_directive'; /* eslint no-console: 0 */ -let notifs = []; -let version = metadata.version; -let buildNum = metadata.buildNum; -let consoleGroups = ('group' in window.console) && ('groupCollapsed' in window.console) && ('groupEnd' in window.console); +const notifs = []; +const version = metadata.version; +const buildNum = metadata.buildNum; +const consoleGroups = ('group' in window.console) && ('groupCollapsed' in window.console) && ('groupEnd' in window.console); -let log = _.bindKey(console, 'log'); +const log = _.bindKey(console, 'log'); // used to identify the first call to fatal, set to false there let firstFatal = true; -let fatalToastTemplate = (function lazyTemplate(tmpl) { +const fatalToastTemplate = (function lazyTemplate(tmpl) { let compiled; return function (vars) { return (compiled || (compiled = _.template(tmpl)))(vars); @@ -34,7 +34,7 @@ function now() { function closeNotif(notif, cb = _.noop, key) { return function () { // this === notif - let i = notifs.indexOf(notif); + const i = notifs.indexOf(notif); if (i !== -1) notifs.splice(i, 1); cancelTimer(notif); @@ -151,7 +151,7 @@ Notifier.prototype.add = add; Notifier.prototype.set = set; function formatInfo() { - let info = []; + const info = []; if (!_.isUndefined(version)) { info.push(`Version: ${version}`); @@ -176,7 +176,7 @@ function formatStack(err) { * Functionality to check that */ function Notifier(opts) { - let self = this; + const self = this; opts = opts || {}; // label type thing to say where notifications came from @@ -254,7 +254,7 @@ Notifier.prototype.lifecycle = createGroupLogger('lifecycle', { * @return {function} - the wrapped function */ Notifier.prototype.timed = function (name, fn) { - let self = this; + const self = this; if (typeof name === 'function') { fn = name; @@ -262,8 +262,8 @@ Notifier.prototype.timed = function (name, fn) { } return function WrappedNotifierFunction() { - let cntx = this; - let args = arguments; + const cntx = this; + const args = arguments; return self.event(name, function () { return fn.apply(cntx, args); @@ -299,7 +299,7 @@ Notifier.prototype._showFatal = function (err) { }); } - let html = fatalToastTemplate({ + const html = fatalToastTemplate({ info: formatInfo(), msg: formatMsg(err, this.from), stack: formatStack(err) @@ -539,7 +539,7 @@ if (log === _.noop) { Notifier.prototype.log = _.noop; } else { Notifier.prototype.log = function () { - let args = [].slice.apply(arguments); + const args = [].slice.apply(arguments); if (this.from) args.unshift(this.from + ':'); log.apply(null, args); }; @@ -548,15 +548,15 @@ if (log === _.noop) { // general functionality used by .event() and .lifecycle() function createGroupLogger(type, opts) { // Track the groups managed by this logger - let groups = window[type + 'Groups'] = {}; + const groups = window[type + 'Groups'] = {}; return function logger(name, success) { let status; // status of the timer let exec; // function to execute and wrap let ret; // return value - let complete = function (val) { logger(name, true); return val; }; - let failure = function (err) { logger(name, false); throw err; }; + const complete = function (val) { logger(name, true); return val; }; + const failure = function (err) { logger(name, false); throw err; }; if (typeof success === 'function' || success === void 0) { // start @@ -572,7 +572,7 @@ function createGroupLogger(type, opts) { } else { groups[name] = now() - (groups[name] || 0); - let time = ' in ' + groups[name].toFixed(2) + 'ms'; + const time = ' in ' + groups[name].toFixed(2) + 'ms'; // end if (success) { diff --git a/src/ui/public/notify/notify.js b/src/ui/public/notify/notify.js index bcfa025cfcdea..76af7d3be906b 100644 --- a/src/ui/public/notify/notify.js +++ b/src/ui/public/notify/notify.js @@ -6,8 +6,8 @@ import Notifier from 'ui/notify/notifier'; import 'ui/notify/directives'; import chrome from 'ui/chrome'; import { kbnIndex } from 'ui/metadata'; -let module = modules.get('kibana/notify'); -let rootNotifier = new Notifier(); +const module = modules.get('kibana/notify'); +const rootNotifier = new Notifier(); module.factory('createNotifier', function () { return function (opts) { diff --git a/src/ui/public/number_list/number_list.js b/src/ui/public/number_list/number_list.js index 9c18da1f3058f..03206d8d4cd01 100644 --- a/src/ui/public/number_list/number_list.js +++ b/src/ui/public/number_list/number_list.js @@ -13,7 +13,7 @@ uiModules controllerAs: 'numberListCntr', require: 'ngModel', controller: function ($scope, $attrs, $parse) { - let self = this; + const self = this; // Called from the pre-link function once we have the controllers self.init = function (modelCntr) { @@ -25,7 +25,7 @@ uiModules self.getUnitName = _.partial($parse($attrs.unit), $scope); - let defaultRange = self.range = parseRange('[0,Infinity)'); + const defaultRange = self.range = parseRange('[0,Infinity)'); $scope.$watch(function () { return $attrs.range; @@ -48,7 +48,7 @@ uiModules * @return {undefined} */ self.remove = function (index) { - let list = self.getList(); + const list = self.getList(); if (!list) return; list.splice(index, 1); @@ -59,7 +59,7 @@ uiModules * @return {undefined} */ self.add = function () { - let list = self.getList(); + const list = self.getList(); if (!list) return; list.push(_.last(list) + 1); diff --git a/src/ui/public/number_list/number_list_input.js b/src/ui/public/number_list/number_list_input.js index 7fbf1b935e02f..21fe02ddf259a 100644 --- a/src/ui/public/number_list/number_list_input.js +++ b/src/ui/public/number_list/number_list_input.js @@ -3,11 +3,11 @@ import _ from 'lodash'; import keyMap from 'ui/utils/key_map'; import uiModules from 'ui/modules'; -let INVALID = {}; // invalid flag -let FLOATABLE = /^[\d\.e\-\+]+$/i; +const INVALID = {}; // invalid flag +const FLOATABLE = /^[\d\.e\-\+]+$/i; -let VALIDATION_ERROR = 'numberListRangeAndOrder'; -let DIRECTIVE_ATTR = 'kbn-number-list-input'; +const VALIDATION_ERROR = 'numberListRangeAndOrder'; +const DIRECTIVE_ATTR = 'kbn-number-list-input'; uiModules .get('kibana') @@ -16,13 +16,13 @@ uiModules restrict: 'A', require: ['ngModel', '^kbnNumberList'], link: function ($scope, $el, attrs, controllers) { - let ngModelCntr = controllers[0]; - let numberListCntr = controllers[1]; + const ngModelCntr = controllers[0]; + const numberListCntr = controllers[1]; - let $setModel = $parse(attrs.ngModel).assign; - let $repeater = $el.closest('[ng-repeat]'); + const $setModel = $parse(attrs.ngModel).assign; + const $repeater = $el.closest('[ng-repeat]'); - let handlers = { + const handlers = { up: change(add, 1), 'shift-up': change(addTenth, 1), @@ -54,14 +54,14 @@ uiModules function go(dir) { return function () { - let $to = $get(dir); + const $to = $get(dir); if ($to.size()) $to.focus(); else return false; }; } function idKey(event) { - let id = []; + const id = []; if (event.ctrlKey) id.push('ctrl'); if (event.shiftKey) id.push('shift'); if (event.metaKey) id.push('meta'); @@ -93,11 +93,11 @@ uiModules function change(using, mod) { return function () { - let str = String(ngModelCntr.$viewValue); - let val = parse(str); + const str = String(ngModelCntr.$viewValue); + const val = parse(str); if (val === INVALID) return; - let next = using(mod, val, str); + const next = using(mod, val, str); if (next === INVALID) return; $el.val(next); @@ -106,7 +106,7 @@ uiModules } function onKeydown(event) { - let handler = handlers[idKey(event)]; + const handler = handlers[idKey(event)]; if (!handler) return; if (handler(event) !== false) { @@ -133,13 +133,13 @@ uiModules if (isNaN(num)) return INVALID; } - let range = numberListCntr.range; + const range = numberListCntr.range; if (!range.within(num)) return INVALID; if ($scope.$index > 0) { - let i = $scope.$index - 1; - let list = numberListCntr.getList(); - let prev = list[i]; + const i = $scope.$index - 1; + const list = numberListCntr.getList(); + const prev = list[i]; if (num <= prev) return INVALID; } @@ -155,14 +155,14 @@ uiModules } } ], function () { - let valid = parse(ngModelCntr.$viewValue) !== INVALID; + const valid = parse(ngModelCntr.$viewValue) !== INVALID; ngModelCntr.$setValidity(VALIDATION_ERROR, valid); }); function validate(then) { return function (input) { let value = parse(input); - let valid = value !== INVALID; + const valid = value !== INVALID; value = valid ? value : input; ngModelCntr.$setValidity(VALIDATION_ERROR, valid); then && then(input, value); diff --git a/src/ui/public/paginated_table/__tests__/index.js b/src/ui/public/paginated_table/__tests__/index.js index 945118d794a70..08057156b65a4 100644 --- a/src/ui/public/paginated_table/__tests__/index.js +++ b/src/ui/public/paginated_table/__tests__/index.js @@ -13,9 +13,9 @@ describe('paginated table', function () { let $scope; let $elScope; let $orderBy; - let defaultPerPage = 10; + const defaultPerPage = 10; - let makeData = function (colCount, rowCount) { + const makeData = function (colCount, rowCount) { let columns = []; let rows = []; @@ -29,7 +29,7 @@ describe('paginated table', function () { if (_.isNumber(rowCount)) { _.times(rowCount, function (col) { - let rowItems = []; + const rowItems = []; _.times(columns.length, function (row) { rowItems.push('item' + col + row); @@ -47,7 +47,7 @@ describe('paginated table', function () { }; }; - let renderTable = function (cols, rows, perPage, sort) { + const renderTable = function (cols, rows, perPage, sort) { $scope.cols = cols || []; $scope.rows = rows || []; $scope.perPage = perPage || defaultPerPage; @@ -68,23 +68,23 @@ describe('paginated table', function () { describe('rendering', function () { it('should not display without rows', function () { - let cols = [{ + const cols = [{ title: 'test1' }]; - let rows = []; + const rows = []; renderTable(cols, rows); expect($el.children().size()).to.be(0); }); it('should render columns and rows', function () { - let data = makeData(2, 2); - let cols = data.columns; - let rows = data.rows; + const data = makeData(2, 2); + const cols = data.columns; + const rows = data.rows; renderTable(cols, rows); expect($el.children().size()).to.be(1); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); // should pad rows expect(tableRows.size()).to.be(defaultPerPage); // should contain the row data @@ -96,13 +96,13 @@ describe('paginated table', function () { it('should paginate rows', function () { // note: paginate truncates pages, so don't make too many - let rowCount = _.random(16, 24); - let perPageCount = _.random(5, 8); - let data = makeData(3, rowCount); - let pageCount = Math.ceil(rowCount / perPageCount); + const rowCount = _.random(16, 24); + const perPageCount = _.random(5, 8); + const data = makeData(3, rowCount); + const pageCount = Math.ceil(rowCount / perPageCount); renderTable(data.columns, data.rows, perPageCount); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.size()).to.be(perPageCount); // add 2 for the first and last page links expect($el.find('paginate-controls a').size()).to.be(pageCount + 2); @@ -132,7 +132,7 @@ describe('paginated table', function () { // }); it('should not sort by default', function () { - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be(data.rows[0][0]); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be(data.rows[lastRowIndex][0]); }); @@ -142,7 +142,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(999); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('zzzz'); @@ -155,7 +155,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('zzzz'); @@ -165,7 +165,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); @@ -175,7 +175,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1, 'desc'); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('zzzz'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('bbbb'); @@ -186,7 +186,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('aaaa'); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('zzzz'); }); @@ -197,7 +197,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('zzzz'); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('aaaa'); }); @@ -209,7 +209,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be(data.rows[0][0]); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('aaaa'); }); @@ -223,7 +223,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(lastRowIndex).find('td').eq(1).text()).to.be('zzzz'); }); @@ -233,15 +233,15 @@ describe('paginated table', function () { describe('sorting duplicate columns', function () { let data; let paginatedTable; - let colText = 'test row'; + const colText = 'test row'; beforeEach(function () { - let cols = [ + const cols = [ { title: colText }, { title: colText }, { title: colText } ]; - let rows = [ + const rows = [ ['bbbb', 'aaaa', 'zzzz'], ['cccc', 'cccc', 'aaaa'], ['zzzz', 'bbbb', 'bbbb'], @@ -254,7 +254,7 @@ describe('paginated table', function () { }); it('should have duplicate column titles', function () { - let columns = $el.find('thead th span'); + const columns = $el.find('thead th span'); columns.each(function () { expect($(this).text()).to.be(colText); }); @@ -265,7 +265,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(2); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('cccc'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('aaaa'); @@ -302,7 +302,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let sorters = $el.find('thead th i'); + const sorters = $el.find('thead th i'); expect(sorters.eq(0).hasClass('fa-sort')).to.be(true); expect(sorters.eq(1).hasClass('fa-sort')).to.be(false); expect(sorters.eq(2).hasClass('fa-sort')).to.be(true); @@ -333,7 +333,7 @@ describe('paginated table', function () { }); it('should append object markup', function () { - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('h1').size()).to.be(0); expect(tableRows.eq(1).find('h1').size()).to.be(1); expect(tableRows.eq(2).find('h1').size()).to.be(0); diff --git a/src/ui/public/parse_query/lib/from_user.js b/src/ui/public/parse_query/lib/from_user.js index 6aac1f93c0feb..85b1ac423364f 100644 --- a/src/ui/public/parse_query/lib/from_user.js +++ b/src/ui/public/parse_query/lib/from_user.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import DecorateQueryProvider from 'ui/courier/data_source/_decorate_query'; export default function GetQueryFromUser(es, Private) { - let decorateQuery = Private(DecorateQueryProvider); + const decorateQuery = Private(DecorateQueryProvider); /** * Take text from the user and make it into a query object @@ -13,7 +13,7 @@ export default function GetQueryFromUser(es, Private) { return decorateQuery({query_string: {query: text}}); } - let matchAll = getQueryStringQuery('*'); + const matchAll = getQueryStringQuery('*'); // If we get an empty object, treat it as a * if (_.isObject(text)) { diff --git a/src/ui/public/parse_query/parse_query.js b/src/ui/public/parse_query/parse_query.js index 148a2f962f796..8d1ea46ddf4a8 100644 --- a/src/ui/public/parse_query/parse_query.js +++ b/src/ui/public/parse_query/parse_query.js @@ -4,7 +4,7 @@ import uiModules from 'ui/modules'; uiModules .get('kibana') .directive('parseQuery', function (Private) { - let fromUser = Private(ParseQueryLibFromUserProvider); + const fromUser = Private(ParseQueryLibFromUserProvider); return { restrict: 'A', @@ -13,7 +13,7 @@ uiModules 'ngModel': '=' }, link: function ($scope, elem, attr, ngModel) { - let init = function () { + const init = function () { $scope.ngModel = fromUser($scope.ngModel); }; diff --git a/src/ui/public/pattern_checker/pattern_checker.js b/src/ui/public/pattern_checker/pattern_checker.js index 134bfce760f61..bec93a9471ce3 100644 --- a/src/ui/public/pattern_checker/pattern_checker.js +++ b/src/ui/public/pattern_checker/pattern_checker.js @@ -17,7 +17,7 @@ module.directive('patternChecker', function () { controller: function (Notifier, $scope, $timeout, $http) { let validationTimeout; - let notify = new Notifier({ + const notify = new Notifier({ location: 'Add Data' }); diff --git a/src/ui/public/persisted_log/__tests__/persisted_log.js b/src/ui/public/persisted_log/__tests__/persisted_log.js index 11115f087e6f8..eff9efa14870c 100644 --- a/src/ui/public/persisted_log/__tests__/persisted_log.js +++ b/src/ui/public/persisted_log/__tests__/persisted_log.js @@ -8,9 +8,9 @@ let storage; let config; let PersistedLog; -let historyName = 'testHistory'; -let historyLimit = 10; -let payload = [ +const historyName = 'testHistory'; +const historyLimit = 10; +const payload = [ { first: 'clark', last: 'kent' }, { first: 'peter', last: 'parker' }, { first: 'bruce', last: 'wayne' } @@ -41,7 +41,7 @@ describe('PersistedLog', function () { describe('expected API', function () { it('has expected methods', function () { - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); expect(log.add).to.be.a('function'); expect(log.get).to.be.a('function'); @@ -50,17 +50,17 @@ describe('PersistedLog', function () { describe('internal functionality', function () { it('reads from storage', function () { - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); expect(storage.get.calledOnce).to.be(true); expect(storage.get.calledWith(historyName)).to.be(true); }); it('writes to storage', function () { - let log = new PersistedLog(historyName); - let newItem = { first: 'diana', last: 'prince' }; + const log = new PersistedLog(historyName); + const newItem = { first: 'diana', last: 'prince' }; - let data = log.add(newItem); + const data = log.add(newItem); expect(storage.set.calledOnce).to.be(true); expect(data).to.eql([newItem]); @@ -70,19 +70,19 @@ describe('PersistedLog', function () { describe('persisting data', function () { it('fetches records from storage', function () { storage.get.returns(payload); - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); - let items = log.get(); + const items = log.get(); expect(items.length).to.equal(3); expect(items).to.eql(payload); }); it('prepends new records', function () { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName); - let newItem = { first: 'selina', last: 'kyle' }; + const log = new PersistedLog(historyName); + const newItem = { first: 'selina', last: 'kyle' }; - let items = log.add(newItem); + const items = log.add(newItem); expect(items.length).to.equal(payload.length + 1); expect(items[0]).to.eql(newItem); }); @@ -90,40 +90,40 @@ describe('PersistedLog', function () { describe('stack options', function () { it('should observe the maxLength option', function () { - let bulkData = []; + const bulkData = []; for (let i = 0; i < historyLimit; i++) { bulkData.push(['record ' + i]); } storage.get.returns(bulkData); - let log = new PersistedLog(historyName, { maxLength: historyLimit }); + const log = new PersistedLog(historyName, { maxLength: historyLimit }); log.add(['new array 1']); - let items = log.add(['new array 2']); + const items = log.add(['new array 2']); expect(items.length).to.equal(historyLimit); }); it('should observe the filterDuplicates option', function () { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, { filterDuplicates: true }); - let newItem = payload[1]; + const log = new PersistedLog(historyName, { filterDuplicates: true }); + const newItem = payload[1]; - let items = log.add(newItem); + const items = log.add(newItem); expect(items.length).to.equal(payload.length); }); it ('should truncate the list upon initialization if too long', () => { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, {maxLength: 1}); - let items = log.get(); + const log = new PersistedLog(historyName, {maxLength: 1}); + const items = log.get(); expect(items.length).to.equal(1); }); it('should allow a maxLength of 0', () => { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, {maxLength: 0}); - let items = log.get(); + const log = new PersistedLog(historyName, {maxLength: 0}); + const items = log.get(); expect(items.length).to.equal(0); }); }); diff --git a/src/ui/public/persisted_state/__tests__/persisted_state.js b/src/ui/public/persisted_state/__tests__/persisted_state.js index af6a2deb3c9cf..e988bbf473aa7 100644 --- a/src/ui/public/persisted_state/__tests__/persisted_state.js +++ b/src/ui/public/persisted_state/__tests__/persisted_state.js @@ -36,7 +36,7 @@ describe('Persisted State', function () { }); it('should create a state instance with data', function () { - let val = { red: 'blue' }; + const val = { red: 'blue' }; persistedState = new PersistedState(val); expect(persistedState.get()).to.eql(val); @@ -45,7 +45,7 @@ describe('Persisted State', function () { }); it('should create a copy of the state passed in', function () { - let val = { red: 'blue' }; + const val = { red: 'blue' }; persistedState = new PersistedState(val); expect(persistedState.get()).to.eql(val); @@ -53,10 +53,10 @@ describe('Persisted State', function () { }); it('should not throw if creating valid child object', function () { - let run = function () { - let val = { red: 'blue' }; - let path = ['test.path']; - let parent = new PersistedState(); + const run = function () { + const val = { red: 'blue' }; + const path = ['test.path']; + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -64,8 +64,8 @@ describe('Persisted State', function () { }); it('should throw if given an invalid value', function () { - let run = function () { - let val = 'bananas'; + const run = function () { + const val = 'bananas'; new PersistedState(val); }; @@ -75,10 +75,10 @@ describe('Persisted State', function () { }); it('should not throw if given primitive to child', function () { - let run = function () { - let val = 'bananas'; - let path = ['test.path']; - let parent = new PersistedState(); + const run = function () { + const val = 'bananas'; + const path = ['test.path']; + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -86,10 +86,10 @@ describe('Persisted State', function () { }); it('should throw if given an invalid parent object', function () { - let run = function () { - let val = { red: 'blue' }; - let path = ['test.path']; - let parent = {}; + const run = function () { + const val = { red: 'blue' }; + const path = ['test.path']; + const parent = {}; new PersistedState(val, path, parent); }; @@ -99,10 +99,10 @@ describe('Persisted State', function () { }); it('should throw if given a parent without a path', function () { - let run = function () { - let val = { red: 'blue' }; + const run = function () { + const val = { red: 'blue' }; let path; - let parent = new PersistedState(); + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -117,8 +117,8 @@ describe('Persisted State', function () { let childState; it('should not append the child state to the parent, without parent value', function () { - let childIndex = 'i can haz child'; - let persistedState = new PersistedState(); + const childIndex = 'i can haz child'; + const persistedState = new PersistedState(); childState = persistedState.createChild(childIndex); // parent state should not contain the child state @@ -127,9 +127,9 @@ describe('Persisted State', function () { }); it('should not append the child state to the parent, with parent value', function () { - let childIndex = 'i can haz child'; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const childIndex = 'i can haz child'; + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); childState = persistedState.createChild(childIndex); // child state should be empty, we didn't give it any default data @@ -141,14 +141,14 @@ describe('Persisted State', function () { }); it('should append the child state to the parent, with parent and child values', function () { - let childIndex = 'i can haz child'; - let childStateValue = { tacos: 'yes please' }; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const childIndex = 'i can haz child'; + const childStateValue = { tacos: 'yes please' }; + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); childState = persistedState.createChild(childIndex, childStateValue); // parent state should contain the child and its original state value - let parentState = persistedState.get(); + const parentState = persistedState.get(); expect(parentState).to.have.property('original', true); expect(parentState).to.have.property(childIndex); expect(parentState[childIndex]).to.eql(childStateValue); @@ -157,15 +157,15 @@ describe('Persisted State', function () { describe('deep child state creation', function () { it('should delegate get/set calls to parent state', function () { - let children = [{ + const children = [{ path: 'first*child', value: { first: true, second: false } }, { path: 'second child', value: { first: false, second: true } }]; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); // first child is a child of the parent persistedState children[0].instance = persistedState.createChild(children[0].path, children[0].value); @@ -176,7 +176,7 @@ describe('Persisted State', function () { expect(children[1].instance.get()).to.eql(children[1].value); // parent should contain original props and first child path, but not the second child path - let parentState = persistedState.get(); + const parentState = persistedState.get(); _.keys(persistedStateValue).forEach(function (key) { expect(parentState).to.have.property(key); }); @@ -184,28 +184,28 @@ describe('Persisted State', function () { expect(parentState).to.not.have.property(children[1].path); // second child path should be inside the first child - let firstChildState = children[0].instance.get(); + const firstChildState = children[0].instance.get(); expect(firstChildState).to.have.property(children[1].path); expect(firstChildState[children[1].path]).to.eql(children[1].value); // check that the second child is still accessible from the parent instance - let firstChild = persistedState.get(children[0].path); + const firstChild = persistedState.get(children[0].path); expect(firstChild).to.have.property(children[1].path); }); }); describe('child state removal', function () { it('should clear path from parent state', function () { - let persistedState = new PersistedState(); - let childState = persistedState.createChild('child', { userId: 1234 }); + const persistedState = new PersistedState(); + const childState = persistedState.createChild('child', { userId: 1234 }); expect(persistedState.get()).to.eql({ child: { userId: 1234 }}); persistedState.removeChild('child'); expect(persistedState.get()).to.eql({}); }); it('should reset original parent value at path', function () { - let persistedState = new PersistedState({ user: 1234 }); - let childState = persistedState.createChild('user', { id: 5678 }); + const persistedState = new PersistedState({ user: 1234 }); + const childState = persistedState.createChild('user', { id: 5678 }); expect(persistedState.get()).to.eql({ user: { id: 5678 }}); persistedState.removeChild('user'); @@ -213,8 +213,8 @@ describe('Persisted State', function () { }); it('should clear changedState', function () { - let persistedState = new PersistedState({ user: 1234 }); - let childState = persistedState.createChild('user'); + const persistedState = new PersistedState({ user: 1234 }); + const childState = persistedState.createChild('user'); childState.set('name', 'user name'); expect(persistedState.getChanges()).to.eql({ user: { name: 'user name' }}); @@ -225,16 +225,16 @@ describe('Persisted State', function () { describe('deep child state removal', function () { it('should clear path from parent state', function () { - let persistedState = new PersistedState(); - let childState = persistedState.createChild('child.state', { userId: 1234 }); + const persistedState = new PersistedState(); + const childState = persistedState.createChild('child.state', { userId: 1234 }); expect(persistedState.get()).to.eql({ child: { state: { userId: 1234 }}}); persistedState.removeChild('child.state'); expect(persistedState.get()).to.eql({}); }); it('should reset original parent value at path', function () { - let persistedState = new PersistedState({ user: { id: 1234 }}); - let childState = persistedState.createChild('user.id', 5678); + const persistedState = new PersistedState({ user: { id: 1234 }}); + const childState = persistedState.createChild('user.id', 5678); expect(persistedState.get()).to.eql({ user: { id: 5678 }}); persistedState.removeChild('user.id'); @@ -242,8 +242,8 @@ describe('Persisted State', function () { }); it('should reset original parent other values at path', function () { - let persistedState = new PersistedState({ user: { name: 'user' }}); - let childState = persistedState.createChild('user.id', 5678); + const persistedState = new PersistedState({ user: { name: 'user' }}); + const childState = persistedState.createChild('user.id', 5678); expect(persistedState.get()).to.eql({ user: { name: 'user', id: 5678 }}); persistedState.removeChild('user.id'); @@ -251,8 +251,8 @@ describe('Persisted State', function () { }); it('should clear the changed state', function () { - let persistedState = new PersistedState({ user: { id: 1234 }}); - let childState = persistedState.createChild('user.name'); + const persistedState = new PersistedState({ user: { id: 1234 }}); + const childState = persistedState.createChild('user.name'); childState.set('user name'); expect(persistedState.getChanges()).to.eql({ user: { name: 'user name' }}); @@ -264,8 +264,8 @@ describe('Persisted State', function () { describe('child state conditions', function () { it('should be merged with the parent state', function () { - let parent = new PersistedState({ name: 'test' }); - let child = parent.createChild('child', 'value'); + const parent = new PersistedState({ name: 'test' }); + const child = parent.createChild('child', 'value'); expect(parent.get()).to.eql({ name: 'test', child: 'value' @@ -285,8 +285,8 @@ describe('Persisted State', function () { }); it('should give child state precedence', function () { - let parent = new PersistedState({ user: { id: 1234, name: 'test' }}); - let child = parent.createChild('user', { name: 'child test' }); + const parent = new PersistedState({ user: { id: 1234, name: 'test' }}); + const child = parent.createChild('user', { name: 'child test' }); expect(parent.get()).to.eql({ user: { id: 1234, @@ -299,8 +299,8 @@ describe('Persisted State', function () { }); it('should be cleaned up with removeChild', function () { - let parent = new PersistedState({ name: 'test' }); - let child = parent.createChild('child', 'value'); + const parent = new PersistedState({ name: 'test' }); + const child = parent.createChild('child', 'value'); expect(parent.get()).to.eql({ name: 'test', child: 'value' @@ -315,16 +315,16 @@ describe('Persisted State', function () { describe('colliding child paths and parent state values', function () { it('should not change the child path value by default', function () { - let childIndex = 'childTest'; - let persistedStateValue = {}; + const childIndex = 'childTest'; + const persistedStateValue = {}; persistedStateValue[childIndex] = { overlapping_index: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); let state = persistedState.get(); expect(state).to.have.property(childIndex); expect(state[childIndex]).to.eql(persistedStateValue[childIndex]); - let childState = persistedState.createChild(childIndex); + const childState = persistedState.createChild(childIndex); expect(childState.get()).to.eql(persistedStateValue[childIndex]); // make sure the parent state is still the same @@ -334,21 +334,21 @@ describe('Persisted State', function () { }); it('should merge default child state', function () { - let childIndex = 'childTest'; - let childStateValue = { child_index: false }; - let persistedStateValue = {}; + const childIndex = 'childTest'; + const childStateValue = { child_index: false }; + const persistedStateValue = {}; persistedStateValue[childIndex] = { parent_index: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); let state = persistedState.get(); expect(state).to.have.property(childIndex); expect(state[childIndex]).to.eql(persistedStateValue[childIndex]); // pass in child state value - let childState = persistedState.createChild(childIndex, childStateValue); + const childState = persistedState.createChild(childIndex, childStateValue); // parent's default state is merged with child state - let compare = _.merge({}, childStateValue, persistedStateValue[childIndex]); + const compare = _.merge({}, childStateValue, persistedStateValue[childIndex]); expect(childState.get()).to.eql(compare); state = persistedState.get(); expect(state).to.have.property(childIndex); @@ -358,11 +358,11 @@ describe('Persisted State', function () { describe('mutation', function () { it('should not mutate the internal object', function () { - let persistedStateValue = { hello: 'world' }; - let insertedObj = { farewell: 'cruel world' }; - let persistedState = new PersistedState(persistedStateValue); + const persistedStateValue = { hello: 'world' }; + const insertedObj = { farewell: 'cruel world' }; + const persistedState = new PersistedState(persistedStateValue); - let obj = persistedState.get(); + const obj = persistedState.get(); _.assign(obj, insertedObj); expect(obj).to.have.property('farewell'); @@ -379,38 +379,38 @@ describe('Persisted State', function () { describe('exporting state to JSON', function () { it('should return the full JSON representation', function () { - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); - let json = persistedState.toJSON(); + const json = persistedState.toJSON(); expect(json).to.eql(persistedStateValue); }); it('should return the JSON representation of the child state', function () { - let persistedState = new PersistedState(persistedStateValue); - let childState = persistedState.createChild('awesome', { pants: false }); + const persistedState = new PersistedState(persistedStateValue); + const childState = persistedState.createChild('awesome', { pants: false }); expect(childState.toJSON()).to.eql({ pants: false }); // verify JSON output of the parent state - let parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); + const parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); expect(persistedState.toJSON()).to.eql(parentCompare); }); it('should export stringified version of state', function () { - let persistedState = new PersistedState(persistedStateValue); - let childState = persistedState.createChild('awesome', { pants: false }); + const persistedState = new PersistedState(persistedStateValue); + const childState = persistedState.createChild('awesome', { pants: false }); - let data = childState.toString(); + const data = childState.toString(); expect(JSON.parse(data)).to.eql({ pants: false }); // verify JSON output of the parent state - let parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); + const parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); expect(JSON.parse(persistedState.toString())).to.eql(parentCompare); }); }); describe('importing state from JSON string (hydration)', function () { it('should set the state from JSON string input', function () { - let stateJSON = JSON.stringify(persistedStateValue); - let persistedState = new PersistedState(); + const stateJSON = JSON.stringify(persistedStateValue); + const persistedState = new PersistedState(); expect(persistedState.get()).to.eql({}); persistedState.fromString(stateJSON); @@ -421,7 +421,7 @@ describe('Persisted State', function () { describe('get state', function () { it('should perform deep gets with various formats', function () { - let obj = { + const obj = { red: { green: { blue: 'yellow' @@ -432,7 +432,7 @@ describe('Persisted State', function () { violet: '' } }; - let persistedState = new PersistedState(obj); + const persistedState = new PersistedState(obj); expect(persistedState.get()).to.eql(obj); expect(persistedState.get('red')).to.eql({ green: { blue: 'yellow' } }); @@ -451,7 +451,7 @@ describe('Persisted State', function () { }); it('should perform deep gets with arrays', function () { - let persistedState = new PersistedState({ hello: { nouns: ['world', 'humans', 'everyone'] } }); + const persistedState = new PersistedState({ hello: { nouns: ['world', 'humans', 'everyone'] } }); expect(persistedState.get()).to.eql({ hello: { nouns: ['world', 'humans', 'everyone'] } }); expect(persistedState.get('hello')).to.eql({ nouns: ['world', 'humans', 'everyone'] }); @@ -459,9 +459,9 @@ describe('Persisted State', function () { }); it('should pass defaults to parent delegation', function () { - let persistedState = new PersistedState({ parent: true }); - let childState = persistedState.createChild('child', { account: { name: 'first child' }}); - let defaultValue = 'i have no data'; + const persistedState = new PersistedState({ parent: true }); + const childState = persistedState.createChild('child', { account: { name: 'first child' }}); + const defaultValue = 'i have no data'; expect(childState.get('account.name', defaultValue)).to.eql('first child'); expect(childState.get('account.age', defaultValue)).to.eql(defaultValue); @@ -471,25 +471,25 @@ describe('Persisted State', function () { describe('set state', function () { describe('path format support', function () { it('should create deep objects from dot notation', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set('one.two.three', 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects from array notation', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set('one[two][three]', 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects from arrays', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set(['one', 'two', 'three'], 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects with an existing path', function () { - let persistedState = new PersistedState({}, 'deep.path'); + const persistedState = new PersistedState({}, 'deep.path'); persistedState.set('green[red].blue', 4); expect(persistedState.get()).to.eql({ green: { red: { blue: 4 } }}); }); @@ -555,19 +555,19 @@ describe('Persisted State', function () { describe('internal state tracking', function () { it('should be an empty object', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); expect(persistedState._defaultState).to.eql({}); }); it('should store the default state value', function () { - let val = { one: 1, two: 2 }; - let persistedState = new PersistedState(val); + const val = { one: 1, two: 2 }; + const persistedState = new PersistedState(val); expect(persistedState._defaultState).to.eql(val); }); it('should keep track of changes', function () { - let val = { one: 1, two: 2 }; - let persistedState = new PersistedState(val); + const val = { one: 1, two: 2 }; + const persistedState = new PersistedState(val); persistedState.set('two', 22); expect(persistedState._defaultState).to.eql(val); @@ -579,14 +579,14 @@ describe('Persisted State', function () { let persistedState; let emitter; - let getByType = function (type, spy) { + const getByType = function (type, spy) { spy = spy || emitter; return spy.getCalls().filter(function (call) { return call.args[0] === type; }); }; - let watchEmitter = function (state) { + const watchEmitter = function (state) { return sinon.spy(state, 'emit'); }; @@ -667,7 +667,7 @@ describe('Persisted State', function () { }); it('should emit on parent and child instances', function (done) { - let child = persistedState.createChild('checker'); + const child = persistedState.createChild('checker'); expect(getByType('change')).to.have.length(0); // parent and child should emit, set up listener to test diff --git a/src/ui/public/persisted_state/persisted_state.js b/src/ui/public/persisted_state/persisted_state.js index 3975c20c24ea6..2df7e511d5ea9 100644 --- a/src/ui/public/persisted_state/persisted_state.js +++ b/src/ui/public/persisted_state/persisted_state.js @@ -5,7 +5,7 @@ import SimpleEmitter from 'ui/utils/simple_emitter'; import EventsProvider from 'ui/events'; export default function (Private) { - let Events = Private(EventsProvider); + const Events = Private(EventsProvider); function validateParent(parent, path) { if (path.length <= 0) { @@ -17,7 +17,7 @@ export default function (Private) { } function validateValue(value) { - let msg = 'State value must be a plain object'; + const msg = 'State value must be a plain object'; if (!value) return; if (!_.isPlainObject(value)) throw new errors.PersistedStateError(msg); } @@ -73,21 +73,21 @@ export default function (Private) { }; PersistedState.prototype.set = function (key, value) { - let params = prepSetParams(key, value, this._path); - let val = this._set(params.key, params.value); + const params = prepSetParams(key, value, this._path); + const val = this._set(params.key, params.value); this.emit('set'); return val; }; PersistedState.prototype.setSilent = function (key, value) { - let params = prepSetParams(key, value, this._path); + const params = prepSetParams(key, value, this._path); return this._set(params.key, params.value, true); }; PersistedState.prototype.reset = function (path) { - let keyPath = this._getIndex(path); - let origValue = _.get(this._defaultState, keyPath); - let currentValue = _.get(this._mergedState, keyPath); + const keyPath = this._getIndex(path); + const origValue = _.get(this._defaultState, keyPath); + const currentValue = _.get(this._mergedState, keyPath); if (_.isUndefined(origValue)) { this._cleanPath(path, this._mergedState); @@ -108,7 +108,7 @@ export default function (Private) { }; PersistedState.prototype.removeChild = function (path) { - let origValue = _.get(this._defaultState, this._getIndex(path)); + const origValue = _.get(this._defaultState, this._getIndex(path)); if (_.isUndefined(origValue)) { this.reset(path); @@ -139,19 +139,19 @@ export default function (Private) { }; PersistedState.prototype._getPartialIndex = function (key) { - let keyPath = this._getIndex(key); + const keyPath = this._getIndex(key); return keyPath.slice(this._path.length); }; PersistedState.prototype._cleanPath = function (path, stateTree) { - let partialPath = this._getPartialIndex(path); + const partialPath = this._getPartialIndex(path); let remove = true; // recursively delete value tree, when no other keys exist while (partialPath.length > 0) { - let lastKey = partialPath.splice(partialPath.length - 1, 1)[0]; - let statePath = this._path.concat(partialPath); - let stateVal = statePath.length > 0 ? _.get(stateTree, statePath) : stateTree; + const lastKey = partialPath.splice(partialPath.length - 1, 1)[0]; + const statePath = this._path.concat(partialPath); + const stateVal = statePath.length > 0 ? _.get(stateTree, statePath) : stateTree; // if stateVal isn't an object, do nothing if (!_.isPlainObject(stateVal)) return; @@ -162,13 +162,13 @@ export default function (Private) { }; PersistedState.prototype._getDefault = function () { - let def = (this._hasPath()) ? undefined : {}; + const def = (this._hasPath()) ? undefined : {}; return (this._parent ? this.get() : def); }; PersistedState.prototype._setPath = function (path) { - let isString = _.isString(path); - let isArray = _.isArray(path); + const isString = _.isString(path); + const isArray = _.isArray(path); if (!isString && !isArray) return []; return (isString) ? [this._getIndex(path)] : path; @@ -196,11 +196,11 @@ export default function (Private) { }; PersistedState.prototype._set = function (key, value, silent, initialChildState) { - let self = this; + const self = this; let stateChanged = false; - let initialState = !this._initialized; - let keyPath = this._getIndex(key); - let hasKeyPath = keyPath.length > 0; + const initialState = !this._initialized; + const keyPath = this._getIndex(key); + const hasKeyPath = keyPath.length > 0; // if this is the initial state value, save value as the default if (initialState) { @@ -226,7 +226,7 @@ export default function (Private) { } } else { // check for changes at path, emit an event when different - let curVal = hasKeyPath ? this.get(keyPath) : this._mergedState; + const curVal = hasKeyPath ? this.get(keyPath) : this._mergedState; stateChanged = !_.isEqual(curVal, value); if (!initialChildState) { @@ -243,11 +243,11 @@ export default function (Private) { } // update the merged state value - let targetObj = this._mergedState || _.cloneDeep(this._defaultState); - let sourceObj = _.merge({}, this._defaultChildState, this._changedState); + const targetObj = this._mergedState || _.cloneDeep(this._defaultState); + const sourceObj = _.merge({}, this._defaultChildState, this._changedState); // handler arguments are (targetValue, sourceValue, key, target, source) - let mergeMethod = function (targetValue, sourceValue, mergeKey) { + const mergeMethod = function (targetValue, sourceValue, mergeKey) { // if not initial state, skip default merge method (ie. return value, see note below) if (!initialState && !initialChildState && _.isEqual(keyPath, self._getIndex(mergeKey))) { // use the sourceValue or fall back to targetValue diff --git a/src/ui/public/private/__tests__/private.js b/src/ui/public/private/__tests__/private.js index fc3dab39d3436..0efb5ac1fc110 100644 --- a/src/ui/public/private/__tests__/private.js +++ b/src/ui/public/private/__tests__/private.js @@ -11,12 +11,12 @@ describe('Private module loader', function () { })); it('accepts a provider that will be called to init a module', function () { - let football = {}; + const football = {}; function Provider() { return football; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(football); }); @@ -25,25 +25,25 @@ describe('Private module loader', function () { return Private; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(Private); }); it('detects circular dependencies', function () { expect(function () { function Provider1() { - let p3 = Private(Provider3); + const p3 = Private(Provider3); } function Provider2() { - let p3 = Private(Provider3); + const p3 = Private(Provider3); } function Provider3() { - let p1 = Private(Provider3); + const p1 = Private(Provider3); } - let p1 = Private(Provider1); + const p1 = Private(Provider1); }).to.throwException(/circular/i); }); @@ -57,24 +57,24 @@ describe('Private module loader', function () { describe('#stub', function () { it('accepts a replacement instance for a Provider', function () { - let replaced = {}; - let replacement = {}; + const replaced = {}; + const replacement = {}; function Provider() { return replaced; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(replaced); Private.stub(Provider, replacement); - let instance2 = Private(Provider); + const instance2 = Private(Provider); expect(instance2).to.be(replacement); Private.stub(Provider, replaced); - let instance3 = Private(Provider); + const instance3 = Private(Provider); expect(instance3).to.be(replaced); }); }); @@ -89,18 +89,18 @@ describe('Private module loader', function () { return {}; } - let instance1 = Private(Provider1); + const instance1 = Private(Provider1); expect(instance1).to.be.an('object'); Private.swap(Provider1, Provider2); - let instance2 = Private(Provider1); + const instance2 = Private(Provider1); expect(instance2).to.be.an('object'); expect(instance2).to.not.be(instance1); Private.swap(Provider1, Provider1); - let instance3 = Private(Provider1); + const instance3 = Private(Provider1); expect(instance3).to.be(instance1); }); @@ -115,12 +115,12 @@ describe('Private module loader', function () { }; } - let instance1 = Private(Provider1); + const instance1 = Private(Provider1); expect(instance1).to.be.an('object'); Private.swap(Provider1, Provider2); - let instance2 = Private(Provider1); + const instance2 = Private(Provider1); expect(instance2).to.have.property('instance1'); expect(instance2.instance1).to.be(instance1); }); diff --git a/src/ui/public/private/private.js b/src/ui/public/private/private.js index 4c371da82cc47..9359fd8f9e6d7 100644 --- a/src/ui/public/private/private.js +++ b/src/ui/public/private/private.js @@ -87,7 +87,7 @@ import uiModules from 'ui/modules'; */ -let nextId = _.partial(_.uniqueId, 'privateProvider#'); +const nextId = _.partial(_.uniqueId, 'privateProvider#'); function name(fn) { return fn.name || fn.toString().split('\n').shift(); @@ -95,11 +95,11 @@ function name(fn) { uiModules.get('kibana') .provider('Private', function () { - let provider = this; + const provider = this; // one cache/swaps per Provider - let cache = {}; - let swaps = {}; + const cache = {}; + const swaps = {}; // return the uniq id for this function function identify(fn) { @@ -117,15 +117,15 @@ uiModules.get('kibana') }; provider.swap = function (fn, prov) { - let id = identify(fn); + const id = identify(fn); swaps[id] = prov; }; provider.$get = ['$injector', function PrivateFactory($injector) { // prevent circular deps by tracking where we came from - let privPath = []; - let pathToString = function () { + const privPath = []; + const pathToString = function () { return privPath.map(name).join(' -> '); }; @@ -140,7 +140,7 @@ uiModules.get('kibana') privPath.push(prov); - let context = {}; + const context = {}; let instance = $injector.invoke(prov, context, locals); if (!_.isObject(instance)) instance = context; diff --git a/src/ui/public/promises/__tests__/promises.js b/src/ui/public/promises/__tests__/promises.js index 9ded576e76cf3..f623e54da5f64 100644 --- a/src/ui/public/promises/__tests__/promises.js +++ b/src/ui/public/promises/__tests__/promises.js @@ -31,8 +31,8 @@ describe('Promise service', function () { }); it('rejects if the callback receives an error', function () { - let errback = sinon.stub(); - let err = new Error(); + const errback = sinon.stub(); + const err = new Error(); Promise.fromNode(cb => cb(err)).catch(errback); $rootScope.$apply(); @@ -41,8 +41,8 @@ describe('Promise service', function () { }); it('resolves with the second argument', function () { - let thenback = sinon.stub(); - let result = {}; + const thenback = sinon.stub(); + const result = {}; Promise.fromNode(cb => cb(null, result)).then(thenback); $rootScope.$apply(); @@ -51,9 +51,9 @@ describe('Promise service', function () { }); it('resolves with an array if multiple arguments are received', function () { - let thenback = sinon.stub(); - let result1 = {}; - let result2 = {}; + const thenback = sinon.stub(); + const result1 = {}; + const result2 = {}; Promise.fromNode(cb => cb(null, result1, result2)).then(thenback); $rootScope.$apply(); @@ -63,7 +63,7 @@ describe('Promise service', function () { }); it('resolves with an array if multiple undefined are received', function () { - let thenback = sinon.stub(); + const thenback = sinon.stub(); Promise.fromNode(cb => cb(null, undefined, undefined)).then(thenback); $rootScope.$apply(); diff --git a/src/ui/public/promises/promises.js b/src/ui/public/promises/promises.js index a2d1ef5249c28..8e3ed9c0b3f17 100644 --- a/src/ui/public/promises/promises.js +++ b/src/ui/public/promises/promises.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // Provides a tiny subset of the excelent API from // bluebird, reimplemented using the $q service @@ -9,7 +9,7 @@ module.service('Promise', function ($q, $timeout) { function Promise(fn) { if (typeof this === 'undefined') throw new Error('Promise constructor must be called with "new"'); - let defer = $q.defer(); + const defer = $q.defer(); try { fn(defer.resolve, defer.reject); } catch (e) { @@ -20,12 +20,12 @@ module.service('Promise', function ($q, $timeout) { Promise.all = Promise.props = $q.all; Promise.resolve = function (val) { - let defer = $q.defer(); + const defer = $q.defer(); defer.resolve(val); return defer.promise; }; Promise.reject = function (reason) { - let defer = $q.defer(); + const defer = $q.defer(); defer.reject(reason); return defer.promise; }; @@ -36,7 +36,7 @@ module.service('Promise', function ($q, $timeout) { }; Promise.method = function (fn) { return function () { - let args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); return Promise.try(fn, args, this); }; }; @@ -51,7 +51,7 @@ module.service('Promise', function ($q, $timeout) { })); }; Promise.each = function (arr, fn) { - let queue = arr.slice(0); + const queue = arr.slice(0); let i = 0; return (function next() { if (!queue.length) return arr; @@ -64,7 +64,7 @@ module.service('Promise', function ($q, $timeout) { return obj && typeof obj.then === 'function'; }; Promise.halt = _.once(function () { - let promise = new Promise(); + const promise = new Promise(); promise.then = _.constant(promise); promise.catch = _.constant(promise); return promise; @@ -155,7 +155,7 @@ module.factory('PromiseEmitter', function (Promise) { * @return {Promise} */ function PromiseEmitter(fn, handler) { - let prom = new Promise(fn); + const prom = new Promise(fn); if (!handler) return prom; diff --git a/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js b/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js index 576fa9f0bd9ae..1b1f8bafba505 100644 --- a/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js +++ b/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js @@ -8,11 +8,11 @@ import EventsProvider from 'ui/events'; import ReflowWatcherProvider from 'ui/reflow_watcher'; describe('Reflow watcher', function () { - let $body = $(document.body); - let $window = $(window); - let expectStubbedEventAndEl = function (stub, event, $el) { + const $body = $(document.body); + const $window = $(window); + const expectStubbedEventAndEl = function (stub, event, $el) { expect(stub.getCalls().some(function (call) { - let events = call.args[0].split(' '); + const events = call.args[0].split(' '); return _.contains(events, event) && $el.is(call.thisValue); })).to.be(true); }; @@ -70,7 +70,7 @@ describe('Reflow watcher', function () { }); it('triggers the "reflow" event within a new angular tick', function () { - let stub = sinon.stub(); + const stub = sinon.stub(); reflowWatcher.on('reflow', stub); reflowWatcher.trigger(); diff --git a/src/ui/public/reflow_watcher/reflow_watcher.js b/src/ui/public/reflow_watcher/reflow_watcher.js index 2592cc9e4bc12..d825e94d9c7e5 100644 --- a/src/ui/public/reflow_watcher/reflow_watcher.js +++ b/src/ui/public/reflow_watcher/reflow_watcher.js @@ -4,12 +4,12 @@ import _ from 'lodash'; import EventsProvider from 'ui/events'; export default function ReflowWatcherService(Private, $rootScope, $http) { - let EventEmitter = Private(EventsProvider); - let $body = $(document.body); - let $window = $(window); + const EventEmitter = Private(EventsProvider); + const $body = $(document.body); + const $window = $(window); - let MOUSE_EVENTS = 'mouseup'; - let WINDOW_EVENTS = 'resize'; + const MOUSE_EVENTS = 'mouseup'; + const WINDOW_EVENTS = 'resize'; _.class(ReflowWatcher).inherits(EventEmitter); /** diff --git a/src/ui/public/registry/__tests__/index.js b/src/ui/public/registry/__tests__/index.js index 85091d32bc754..aaf1f69b115b5 100644 --- a/src/ui/public/registry/__tests__/index.js +++ b/src/ui/public/registry/__tests__/index.js @@ -13,14 +13,14 @@ describe('Registry', function () { })); it('is technically a function', function () { - let reg = registry(); + const reg = registry(); expect(reg).to.be.a('function'); }); describe('#register', function () { it('accepts a Private module', function () { - let reg = registry(); - let mod = function SomePrivateModule() {}; + const reg = registry(); + const mod = function SomePrivateModule() {}; reg.register(mod); // modules are not exposed, so this is the most that we can test @@ -29,13 +29,13 @@ describe('Registry', function () { describe('as a module', function () { it('exposes the list of registered modules', function () { - let reg = registry(); - let mod = function SomePrivateModule(Private) { + const reg = registry(); + const mod = function SomePrivateModule(Private) { this.PrivateModuleLoader = Private; }; reg.register(mod); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.have.length(1); expect(modules[0]).to.have.property('PrivateModuleLoader', Private); }); @@ -43,16 +43,16 @@ describe('Registry', function () { describe('spec', function () { it('executes with the module list as "this", and can override it', function () { - let i = 0; + const i = 0; let self; - let reg = registry({ + const reg = registry({ constructor: function () { return { mods: (self = this) }; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.be.an('object'); expect(modules).to.have.property('mods', self); }); @@ -60,7 +60,7 @@ describe('Registry', function () { describe('spec.name', function () { it('sets the displayName of the registry and the name param on the final instance', function () { - let reg = registry({ + const reg = registry({ name: 'visTypes' }); @@ -72,27 +72,27 @@ describe('Registry', function () { describe('spec.constructor', function () { it('executes before the modules are returned', function () { let i = 0; - let reg = registry({ + const reg = registry({ constructor: function () { i = i + 1; } }); - let modules = Private(reg); + const modules = Private(reg); expect(i).to.be(1); }); it('executes with the module list as "this", and can override it', function () { - let i = 0; + const i = 0; let self; - let reg = registry({ + const reg = registry({ constructor: function () { return { mods: (self = this) }; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.be.an('object'); expect(modules).to.have.property('mods', self); }); @@ -100,13 +100,13 @@ describe('Registry', function () { describe('spec[any]', function () { it('mixes the extra properties into the module list', function () { - let reg = registry({ + const reg = registry({ someMethod: function () { return this; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.have.property('someMethod'); expect(modules.someMethod()).to.be(modules); }); diff --git a/src/ui/public/registry/_registry.js b/src/ui/public/registry/_registry.js index 396ad08237ed8..c5aa8ec454bc2 100644 --- a/src/ui/public/registry/_registry.js +++ b/src/ui/public/registry/_registry.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexedArray from 'ui/indexed_array'; import RegistryVisTypesProvider from 'ui/registry/vis_types'; -let notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); +const notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); /** * Create a registry, which is just a Private module provider. @@ -49,10 +49,10 @@ let notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); export default function createRegistry(spec) { spec = spec || {}; - let constructor = _.has(spec, 'constructor') && spec.constructor; - let iaOpts = _.defaults(_.pick(spec, IndexedArray.OPT_NAMES), { index: ['name'] }); - let props = _.omit(spec, notPropsOptNames); - let providers = []; + const constructor = _.has(spec, 'constructor') && spec.constructor; + const iaOpts = _.defaults(_.pick(spec, IndexedArray.OPT_NAMES), { index: ['name'] }); + const props = _.omit(spec, notPropsOptNames); + const providers = []; /** * This is the Private module that will be instanciated by @@ -62,7 +62,7 @@ export default function createRegistry(spec) { * that were registered, the registry spec * defines how things will be indexed. */ - let registry = function (Private, $injector) { + const registry = function (Private, $injector) { // index all of the modules iaOpts.initialSet = providers.map(Private); let modules = new IndexedArray(iaOpts); diff --git a/src/ui/public/registry/field_formats.js b/src/ui/public/registry/field_formats.js index ca7895faca82f..393f2660afb47 100644 --- a/src/ui/public/registry/field_formats.js +++ b/src/ui/public/registry/field_formats.js @@ -7,7 +7,7 @@ export default uiRegistry({ group: ['fieldType'], constructor: function (config) { - let self = this; + const self = this; let defaultMap; function init() { @@ -54,7 +54,7 @@ export default uiRegistry({ * @return {FieldFormat} */ self.getInstance = _.memoize(function (formatId) { - let FieldFormat = self.byId[formatId]; + const FieldFormat = self.byId[formatId]; return new FieldFormat(); }); @@ -65,8 +65,8 @@ export default uiRegistry({ * @return {FieldFormat} */ self.getDefaultInstance = _.memoize(function (fieldType) { - let conf = self.getDefaultConfig(fieldType); - let FieldFormat = self.byId[conf.id]; + const conf = self.getDefaultConfig(fieldType); + const FieldFormat = self.byId[conf.id]; return new FieldFormat(conf.params); }); diff --git a/src/ui/public/routes/__tests__/_route_manager.js b/src/ui/public/routes/__tests__/_route_manager.js index c854d88325400..b920e5d63dd14 100644 --- a/src/ui/public/routes/__tests__/_route_manager.js +++ b/src/ui/public/routes/__tests__/_route_manager.js @@ -5,7 +5,7 @@ import RouteManager from 'ui/routes/route_manager'; import expect from 'expect.js'; let routes; // will contain an new instance of RouteManager for each test -let chainableMethods = [ +const chainableMethods = [ { name: 'when', args: ['', {}] }, { name: 'otherwise', args: [{}] }, { name: 'defaults', args: [/regexp/, {}] } @@ -31,7 +31,7 @@ describe('routes/route_manager', function () { describe('#otherwise', function () { it('should forward the last otherwise route', function () { - let otherRoute = {}; + const otherRoute = {}; routes.otherwise({}); routes.otherwise(otherRoute); @@ -68,7 +68,7 @@ describe('routes/route_manager', function () { describe('#config', function () { it('should add defined routes to the global $routeProvider service in order', function () { - let args = [ + const args = [ ['/one', {}], ['/two', {}] ]; @@ -81,8 +81,8 @@ describe('routes/route_manager', function () { expect($rp.when.callCount).to.be(args.length); _.times(args.length, function (i) { - let call = $rp.when.getCall(i); - let a = args.shift(); + const call = $rp.when.getCall(i); + const a = args.shift(); expect(call.args[0]).to.be(a[0]); expect(call.args[1]).to.be(a[1]); diff --git a/src/ui/public/routes/__tests__/_work_queue.js b/src/ui/public/routes/__tests__/_work_queue.js index 863f7345075bd..33044daeae835 100644 --- a/src/ui/public/routes/__tests__/_work_queue.js +++ b/src/ui/public/routes/__tests__/_work_queue.js @@ -25,10 +25,10 @@ describe('work queue', function () { describe('#resolveWhenFull', function () { it('resolves requests waiting for the queue to fill when appropriate', function () { - let size = _.random(5, 50); + const size = _.random(5, 50); queue.limit = size; - let whenFull = Promise.defer(); + const whenFull = Promise.defer(); sinon.stub(whenFull, 'resolve'); queue.resolveWhenFull(whenFull); @@ -53,11 +53,11 @@ describe('work queue', function () { * can manipulate the filled queue */ function fillWithStubs(then) { - let size = _.random(5, 50); - let stub = sinon.stub(); + const size = _.random(5, 50); + const stub = sinon.stub(); _.times(size, function () { - let d = Promise.defer(); + const d = Promise.defer(); // overwrite the defer methods with the stub d.resolve = stub; d.reject = stub; diff --git a/src/ui/public/routes/__tests__/_wrap_route_with_prep.js b/src/ui/public/routes/__tests__/_wrap_route_with_prep.js index a56cb503e1d46..8570b3f7cb8c3 100644 --- a/src/ui/public/routes/__tests__/_wrap_route_with_prep.js +++ b/src/ui/public/routes/__tests__/_wrap_route_with_prep.js @@ -18,11 +18,11 @@ describe('wrapRouteWithPrep fn', function () { routes = new RouteManager(); }); - let SchedulingTest = function (opts) { + const SchedulingTest = function (opts) { opts = opts || {}; - let delaySetup = opts.delayUserWork ? 0 : 50; - let delayUserWork = opts.delayUserWork ? 50 : 0; + const delaySetup = opts.delayUserWork ? 0 : 50; + const delayUserWork = opts.delayUserWork ? 50 : 0; return function () { ngMock.module('kibana', 'kibana/notify'); diff --git a/src/ui/public/routes/route_manager.js b/src/ui/public/routes/route_manager.js index e06c9fc6e55d5..22c6c1e518387 100644 --- a/src/ui/public/routes/route_manager.js +++ b/src/ui/public/routes/route_manager.js @@ -4,16 +4,16 @@ import wrapRouteWithPrep from './wrap_route_with_prep'; import RouteSetupManager from './route_setup_manager'; function RouteManager() { - let self = this; - let setup = new RouteSetupManager(); - let when = []; - let defaults = []; + const self = this; + const setup = new RouteSetupManager(); + const when = []; + const defaults = []; let otherwise; self.config = function ($routeProvider) { when.forEach(function (args) { - let path = args[0]; - let route = args[1] || {}; + const path = args[0]; + const route = args[1] || {}; // merge in any defaults defaults.forEach(function (args) { @@ -40,7 +40,7 @@ function RouteManager() { } }; - let wrapSetupAndChain = (fn, ...args) => { + const wrapSetupAndChain = (fn, ...args) => { fn.apply(setup, args); return this; }; diff --git a/src/ui/public/routes/route_setup_manager.js b/src/ui/public/routes/route_setup_manager.js index 1cb89fe456455..15ab1b264149f 100644 --- a/src/ui/public/routes/route_setup_manager.js +++ b/src/ui/public/routes/route_setup_manager.js @@ -30,7 +30,7 @@ module.exports = class RouteSetupManager { */ doWork(Promise, $injector, userWork) { - let invokeEach = (arr, locals) => { + const invokeEach = (arr, locals) => { return Promise.map(arr, fn => { if (!fn) return; return $injector.invoke(fn, null, locals); @@ -39,16 +39,16 @@ module.exports = class RouteSetupManager { // call each error handler in order, until one of them resolves // or we run out of handlers - let callErrorHandlers = (handlers, origError) => { + const callErrorHandlers = (handlers, origError) => { if (!_.size(handlers)) throw origError; // clone so we don't discard handlers or loose them handlers = handlers.slice(0); - let next = (err) => { + const next = (err) => { if (!handlers.length) throw err; - let handler = handlers.shift(); + const handler = handlers.shift(); if (!handler) return next(err); return Promise.try(function () { @@ -66,7 +66,7 @@ module.exports = class RouteSetupManager { ) .then(() => { // wait for the queue to fill up, then do all the work - let defer = Promise.defer(); + const defer = Promise.defer(); userWork.resolveWhenFull(defer); return defer.promise.then(() => Promise.all(userWork.doWork())); diff --git a/src/ui/public/routes/routes.js b/src/ui/public/routes/routes.js index cbb9878df7a1e..077590cafa642 100644 --- a/src/ui/public/routes/routes.js +++ b/src/ui/public/routes/routes.js @@ -1,7 +1,7 @@ import RouteManager from './route_manager'; import 'angular-route/angular-route'; import uiModules from 'ui/modules'; -let defaultRouteManager = new RouteManager(); +const defaultRouteManager = new RouteManager(); module.exports = { ...defaultRouteManager, diff --git a/src/ui/public/routes/work_queue.js b/src/ui/public/routes/work_queue.js index 40f4294327829..05146f6613a07 100644 --- a/src/ui/public/routes/work_queue.js +++ b/src/ui/public/routes/work_queue.js @@ -1,10 +1,10 @@ import _ from 'lodash'; function WorkQueue() { - let q = this; + const q = this; - let work = []; - let fullDefers = []; + const work = []; + const fullDefers = []; q.limit = 0; Object.defineProperty(q, 'length', { @@ -13,13 +13,13 @@ function WorkQueue() { } }); - let resolve = function (defers) { + const resolve = function (defers) { return defers.splice(0).map(function (defer) { return defer.resolve(); }); }; - let checkIfFull = function () { + const checkIfFull = function () { if (work.length >= q.limit && fullDefers.length) { resolve(fullDefers); } @@ -31,7 +31,7 @@ function WorkQueue() { }; q.doWork = function () { - let resps = resolve(work); + const resps = resolve(work); checkIfFull(); return resps; }; diff --git a/src/ui/public/routes/wrap_route_with_prep.js b/src/ui/public/routes/wrap_route_with_prep.js index 5c4b98a82d0a8..6ed3368226af3 100644 --- a/src/ui/public/routes/wrap_route_with_prep.js +++ b/src/ui/public/routes/wrap_route_with_prep.js @@ -7,11 +7,11 @@ import errors from 'ui/errors'; function wrapRouteWithPrep(route, setup) { if (!route.resolve && route.redirectTo) return; - let userWork = new WorkQueue(); + const userWork = new WorkQueue(); // the point at which we will consider the queue "full" userWork.limit = _.keys(route.resolve).length; - let resolve = { + const resolve = { __prep__: function ($injector) { return $injector.invoke(setup.doWork, setup, { userWork }); } @@ -21,7 +21,7 @@ function wrapRouteWithPrep(route, setup) { // prep is complete _.forOwn(route.resolve || {}, function (expr, name) { resolve[name] = function ($injector, Promise) { - let defer = Promise.defer(); + const defer = Promise.defer(); userWork.push(defer); return defer.promise.then(function () { return $injector[angular.isString(expr) ? 'get' : 'invoke'](expr); diff --git a/src/ui/public/stack_trace_mapper/set_error_stack.js b/src/ui/public/stack_trace_mapper/set_error_stack.js index ff6f5b7838455..47e3dacb8aeb0 100644 --- a/src/ui/public/stack_trace_mapper/set_error_stack.js +++ b/src/ui/public/stack_trace_mapper/set_error_stack.js @@ -1,6 +1,6 @@ import _ from 'lodash'; -let err = new Error(); +const err = new Error(); try { setByAssignment(err, 'john'); } catch (e) {} // eslint-disable-line // err.stack is not always writeable, so we @@ -13,7 +13,7 @@ if (err.stack === 'john') module.exports = setByAssignment; else module.exports = setByShadowing; function setByShadowing(err, stack) { - let props = _.mapValues(err, function (val) { + const props = _.mapValues(err, function (val) { return { enumerable: true, value: val diff --git a/src/ui/public/stack_trace_mapper/stack_line_format.js b/src/ui/public/stack_trace_mapper/stack_line_format.js index 7d4c2ebe476c7..aed9949777008 100644 --- a/src/ui/public/stack_trace_mapper/stack_line_format.js +++ b/src/ui/public/stack_trace_mapper/stack_line_format.js @@ -1,6 +1,6 @@ import _ from 'lodash'; -let opts = [ +const opts = [ /@((?:[!#$&-;=?-\[\]_a-z~]|%[0-9a-f]{2})+\.js)\:(\d+)(?:\:(\d+)|())/ig, /(?: \(|at )((?:[!#$&-;=?-\[\]_a-z~]|%[0-9a-f]{2})+\.js)\:(\d+)(?:\:(\d+)|())/ig ]; @@ -8,7 +8,7 @@ let opts = [ let sample; try { throw new Error('msg'); } catch (e) { sample = e.stack; } -let format = _.find(opts, function (format) { +const format = _.find(opts, function (format) { return format.test(sample); }); diff --git a/src/ui/public/stack_trace_mapper/stack_trace_mapper.js b/src/ui/public/stack_trace_mapper/stack_trace_mapper.js index 85b4366184333..348de16e1d99e 100644 --- a/src/ui/public/stack_trace_mapper/stack_trace_mapper.js +++ b/src/ui/public/stack_trace_mapper/stack_trace_mapper.js @@ -22,7 +22,7 @@ StackTraceMapper.prototype.init = function (mapUrls) { StackTraceMapper.prototype.mapError = function (err) { if (!stackLineFormat || !err.stack) return err; - let stack = err.stack.replace(stackLineFormat, this.mapLine); + const stack = err.stack.replace(stackLineFormat, this.mapLine); return setErrorStack(err, stack); }; @@ -39,10 +39,10 @@ StackTraceMapper.prototype.getMapFor = function (url) { StackTraceMapper.prototype.loadMaps = function (mapUrls) { mapUrls = _.clone(mapUrls || {}); - let maps = this.maps; + const maps = this.maps; $('script[src][src-map]').each(function () { - let $el = $(this); + const $el = $(this); mapUrls[$el.attr('src')] = $el.attr('src-map'); }); diff --git a/src/ui/public/stack_trace_mapper/translate_stack_line.js b/src/ui/public/stack_trace_mapper/translate_stack_line.js index f19f64cfe6186..c2a2c313a9a44 100644 --- a/src/ui/public/stack_trace_mapper/translate_stack_line.js +++ b/src/ui/public/stack_trace_mapper/translate_stack_line.js @@ -3,16 +3,16 @@ import _ from 'lodash'; module.exports = function (map, match, filename, line, col) { if (!map) return match; - let position = { + const position = { line: parseFloat(line) || 0, column: parseFloat(col) || 0 }; - let srcPosition = map.smc.originalPositionFor(position); + const srcPosition = map.smc.originalPositionFor(position); if (!srcPosition || !srcPosition.source) return match; - let srcFilename = srcPosition.source; - let srcLine = srcPosition.line; + const srcFilename = srcPosition.source; + const srcLine = srcPosition.line; let srcCol = srcPosition.column; if (srcCol === 0 && position.column) { @@ -28,8 +28,8 @@ module.exports = function (map, match, filename, line, col) { // we don't accidentally replace the wrong part we use splitting and consumption let resp = ''; let remainingResp = match; - let fold = function (replace, replacement) { - let wrappingContent = remainingResp.split(replace); + const fold = function (replace, replacement) { + const wrappingContent = remainingResp.split(replace); resp += wrappingContent.shift() + replacement; remainingResp = wrappingContent.join(replace); }; diff --git a/src/ui/public/state_management/__tests__/app_state.js b/src/ui/public/state_management/__tests__/app_state.js index 6f9af310db4a4..ba4b1310a0f70 100644 --- a/src/ui/public/state_management/__tests__/app_state.js +++ b/src/ui/public/state_management/__tests__/app_state.js @@ -27,7 +27,7 @@ describe('State Management', function () { }); it('should use passed in params', function () { - let params = { + const params = { test: true, mock: false }; @@ -46,8 +46,8 @@ describe('State Management', function () { }); it('should be destroyed on $routeChangeStart', function () { - let destroySpy = sinon.spy(appState, 'destroy'); - let url = '/test/path'; + const destroySpy = sinon.spy(appState, 'destroy'); + const url = '/test/path'; $rootScope.$emit('$routeChangeStart'); diff --git a/src/ui/public/state_management/__tests__/state.js b/src/ui/public/state_management/__tests__/state.js index d0233594e5b44..7224be9cc4623 100644 --- a/src/ui/public/state_management/__tests__/state.js +++ b/src/ui/public/state_management/__tests__/state.js @@ -23,26 +23,26 @@ describe('State Management', function () { describe('Provider', function () { it('should reset the state to the defaults', function () { - let state = new State('_s', { message: ['test'] }); + const state = new State('_s', { message: ['test'] }); state.reset(); - let search = $location.search(); + const search = $location.search(); expect(search).to.have.property('_s'); expect(search._s).to.equal('(message:!(test))'); expect(state.message).to.eql(['test']); }); it('should apply the defaults upon initialization', function () { - let state = new State('_s', { message: 'test' }); + const state = new State('_s', { message: 'test' }); expect(state).to.have.property('message', 'test'); }); it('should inherit from Events', function () { - let state = new State(); + const state = new State(); expect(state).to.be.an(Events); }); it('should emit an event if reset with changes', function (done) { - let state = new State('_s', { message: 'test' }); + const state = new State('_s', { message: 'test' }); state.on('reset_with_changes', function (keys) { expect(keys).to.eql(['message']); done(); @@ -54,7 +54,7 @@ describe('State Management', function () { }); it('should not emit an event if reset without changes', function () { - let state = new State('_s', { message: 'test' }); + const state = new State('_s', { message: 'test' }); state.on('reset_with_changes', function () { expect().fail(); }); @@ -67,29 +67,29 @@ describe('State Management', function () { describe('Search', function () { it('should save to $location.search()', function () { - let state = new State('_s', { test: 'foo' }); + const state = new State('_s', { test: 'foo' }); state.save(); - let search = $location.search(); + const search = $location.search(); expect(search).to.have.property('_s'); expect(search._s).to.equal('(test:foo)'); }); it('should emit an event if changes are saved', function (done) { - let state = new State(); + const state = new State(); state.on('save_with_changes', function (keys) { expect(keys).to.eql(['test']); done(); }); state.test = 'foo'; state.save(); - let search = $location.search(); + const search = $location.search(); $rootScope.$apply(); }); }); describe('Fetch', function () { it('should emit an event if changes are fetched', function (done) { - let state = new State(); + const state = new State(); state.on('fetch_with_changes', function (keys) { expect(keys).to.eql(['foo']); done(); @@ -101,7 +101,7 @@ describe('State Management', function () { }); it('should have events that attach to scope', function (done) { - let state = new State(); + const state = new State(); state.on('test', function (message) { expect(message).to.equal('foo'); done(); @@ -111,7 +111,7 @@ describe('State Management', function () { }); it('should fire listeners for #onUpdate() on #fetch()', function (done) { - let state = new State(); + const state = new State(); state.on('fetch_with_changes', function (keys) { expect(keys).to.eql(['foo']); done(); @@ -123,7 +123,7 @@ describe('State Management', function () { }); it('should apply defaults to fetches', function () { - let state = new State('_s', { message: 'test' }); + const state = new State('_s', { message: 'test' }); $location.search({ _s: '(foo:bar)' }); state.fetch(); expect(state).to.have.property('foo', 'bar'); @@ -131,15 +131,15 @@ describe('State Management', function () { }); it('should call fetch when $routeUpdate is fired on $rootScope', function () { - let state = new State(); - let spy = sinon.spy(state, 'fetch'); + const state = new State(); + const spy = sinon.spy(state, 'fetch'); $rootScope.$emit('$routeUpdate', 'test'); sinon.assert.calledOnce(spy); }); it('should clear state when missing form URL', function () { let stateObj; - let state = new State(); + const state = new State(); // set satte via URL $location.search({ _s: '(foo:(bar:baz))' }); diff --git a/src/ui/public/state_management/app_state.js b/src/ui/public/state_management/app_state.js index c2312c5cdcffa..a77b267cafce2 100644 --- a/src/ui/public/state_management/app_state.js +++ b/src/ui/public/state_management/app_state.js @@ -2,11 +2,11 @@ import _ from 'lodash'; import modules from 'ui/modules'; import StateManagementStateProvider from 'ui/state_management/state'; import PersistedStatePersistedStateProvider from 'ui/persisted_state/persisted_state'; -let urlParam = '_a'; +const urlParam = '_a'; function AppStateProvider(Private, $rootScope, $location) { - let State = Private(StateManagementStateProvider); - let PersistedState = Private(PersistedStatePersistedStateProvider); + const State = Private(StateManagementStateProvider); + const PersistedState = Private(PersistedStatePersistedStateProvider); let persistedStates; let eventUnsubscribers; @@ -30,31 +30,31 @@ function AppStateProvider(Private, $rootScope, $location) { AppState.prototype.makeStateful = function (prop) { if (persistedStates[prop]) return persistedStates[prop]; - let self = this; + const self = this; // set up the ui state persistedStates[prop] = new PersistedState(); // update the app state when the stateful instance changes - let updateOnChange = function () { - let replaceState = false; // TODO: debouncing logic + const updateOnChange = function () { + const replaceState = false; // TODO: debouncing logic self[prop] = persistedStates[prop].getChanges(); self.save(replaceState); }; - let handlerOnChange = (method) => persistedStates[prop][method]('change', updateOnChange); + const handlerOnChange = (method) => persistedStates[prop][method]('change', updateOnChange); handlerOnChange('on'); eventUnsubscribers.push(() => handlerOnChange('off')); // update the stateful object when the app state changes - let persistOnChange = function (changes) { + const persistOnChange = function (changes) { if (!changes) return; if (changes.indexOf(prop) !== -1) { persistedStates[prop].set(self[prop]); } }; - let handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); + const handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); handlePersist('on'); eventUnsubscribers.push(() => handlePersist('off')); @@ -73,7 +73,7 @@ function AppStateProvider(Private, $rootScope, $location) { // Checks to see if the appState might already exist, even if it hasn't been newed up get.previouslyStored = function () { - let search = $location.search(); + const search = $location.search(); return search[urlParam] ? true : false; }; diff --git a/src/ui/public/state_management/global_state.js b/src/ui/public/state_management/global_state.js index 7448822d7b8b8..81c875b086a6f 100644 --- a/src/ui/public/state_management/global_state.js +++ b/src/ui/public/state_management/global_state.js @@ -5,10 +5,10 @@ import rison from 'rison-node'; import StateManagementStateProvider from 'ui/state_management/state'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana/global_state'); +const module = uiModules.get('kibana/global_state'); function GlobalStateProvider(Private, $rootScope, $location) { - let State = Private(StateManagementStateProvider); + const State = Private(StateManagementStateProvider); _.class(GlobalState).inherits(State); function GlobalState(defaults) { diff --git a/src/ui/public/state_management/state.js b/src/ui/public/state_management/state.js index 7b934567e01ff..e86b88d360f5a 100644 --- a/src/ui/public/state_management/state.js +++ b/src/ui/public/state_management/state.js @@ -14,7 +14,7 @@ export default function StateProvider(Private, $rootScope, $location) { function State(urlParam, defaults) { State.Super.call(this); - let self = this; + const self = this; self.setDefaults(defaults); self._urlParam = urlParam || '_s'; @@ -45,7 +45,7 @@ export default function StateProvider(Private, $rootScope, $location) { } State.prototype._readFromURL = function () { - let search = $location.search(); + const search = $location.search(); try { return search[this._urlParam] ? rison.decode(search[this._urlParam]) : null; } catch (e) { @@ -74,7 +74,7 @@ export default function StateProvider(Private, $rootScope, $location) { _.defaults(stash, this._defaults); // apply diff to state from stash, will change state in place via side effect - let diffResults = applyDiff(this, stash); + const diffResults = applyDiff(this, stash); if (diffResults.keys.length) { this.emit('fetch_with_changes', diffResults.keys); @@ -87,7 +87,7 @@ export default function StateProvider(Private, $rootScope, $location) { */ State.prototype.save = function (replace) { let stash = this._readFromURL(); - let state = this.toObject(); + const state = this.toObject(); replace = replace || false; if (!stash) { @@ -97,14 +97,14 @@ export default function StateProvider(Private, $rootScope, $location) { _.defaults(state, this._defaults); // apply diff to state from stash, will change state in place via side effect - let diffResults = applyDiff(stash, state); + const diffResults = applyDiff(stash, state); if (diffResults.keys.length) { this.emit('save_with_changes', diffResults.keys); } // persist the state in the URL - let search = $location.search(); + const search = $location.search(); search[this._urlParam] = this.toRISON(); if (replace) { $location.search(search).replace(); @@ -129,7 +129,7 @@ export default function StateProvider(Private, $rootScope, $location) { State.prototype.reset = function () { // apply diff to _attributes from defaults, this is side effecting so // it will change the state in place. - let diffResults = applyDiff(this, this._defaults); + const diffResults = applyDiff(this, this._defaults); if (diffResults.keys.length) { this.emit('reset_with_changes', diffResults.keys); } diff --git a/src/ui/public/storage/__tests__/storage.js b/src/ui/public/storage/__tests__/storage.js index 8a4d5e2872f7c..f5f5f7a7c425c 100644 --- a/src/ui/public/storage/__tests__/storage.js +++ b/src/ui/public/storage/__tests__/storage.js @@ -5,7 +5,7 @@ import 'ui/storage'; let storage; let $window; -let payload = { first: 'john', last: 'smith' }; +const payload = { first: 'john', last: 'smith' }; function init() { @@ -69,21 +69,21 @@ describe('StorageService', function () { describe('json data', function () { it('should parse JSON when reading from the store', function () { - let getItem = $window.localStorage.getItem; + const getItem = $window.localStorage.getItem; getItem.returns(JSON.stringify(payload)); - let data = storage.get('name'); + const data = storage.get('name'); expect(data).to.eql(payload); }); it('should write JSON string to the store', function () { - let setItem = $window.localStorage.setItem; - let key = 'name'; - let value = payload; + const setItem = $window.localStorage.setItem; + const key = 'name'; + const value = payload; storage.set(key, value); - let call = setItem.getCall(0); + const call = setItem.getCall(0); expect(call.args[0]).to.equal(key); expect(call.args[1]).to.equal(JSON.stringify(value)); }); @@ -91,15 +91,15 @@ describe('StorageService', function () { describe('expected responses', function () { it('should return null when not exists', function () { - let data = storage.get('notexists'); + const data = storage.get('notexists'); expect(data).to.equal(null); }); it('should return null when invalid JSON', function () { - let getItem = $window.localStorage.getItem; + const getItem = $window.localStorage.getItem; getItem.returns('not: json'); - let data = storage.get('name'); + const data = storage.get('name'); expect(data).to.equal(null); }); }); diff --git a/src/ui/public/storage/storage.js b/src/ui/public/storage/storage.js index aa043158724bd..eaa243ed5be1d 100644 --- a/src/ui/public/storage/storage.js +++ b/src/ui/public/storage/storage.js @@ -2,7 +2,7 @@ import modules from 'ui/modules'; import angular from 'angular'; function Storage(store) { - let self = this; + const self = this; self.store = store; self.get = function (key) { @@ -30,7 +30,7 @@ function Storage(store) { }; } -let createService = function (type) { +const createService = function (type) { return function ($window) { return new Storage($window[type]); }; diff --git a/src/ui/public/stringify/__tests__/_color.js b/src/ui/public/stringify/__tests__/_color.js index f48823ea3d5e1..4d3a73eb7b251 100644 --- a/src/ui/public/stringify/__tests__/_color.js +++ b/src/ui/public/stringify/__tests__/_color.js @@ -13,7 +13,7 @@ describe('Color Format', function () { })); it('should add colors if the value is in range', function () { - let colorer = new ColorFormat({ + const colorer = new ColorFormat({ colors: [{ range: '100:150', text: 'blue', @@ -27,7 +27,7 @@ describe('Color Format', function () { }); it('should not convert invalid ranges', function () { - let colorer = new ColorFormat({ + const colorer = new ColorFormat({ colors: [{ range: '100150', text: 'blue', diff --git a/src/ui/public/stringify/__tests__/_date.js b/src/ui/public/stringify/__tests__/_date.js index aec730580bf48..c3a90a2c1d7f1 100644 --- a/src/ui/public/stringify/__tests__/_date.js +++ b/src/ui/public/stringify/__tests__/_date.js @@ -15,8 +15,8 @@ describe('Date Format', function () { settings = config; fieldFormats = Private(RegistryFieldFormatsProvider); - let DateFormat = fieldFormats.getType('date'); - let date = new DateFormat(); + const DateFormat = fieldFormats.getType('date'); + const date = new DateFormat(); convert = date.convert.bind(date); })); @@ -30,17 +30,17 @@ describe('Date Format', function () { function setDefaultTimezone() { moment.tz.setDefault(settings.get('dateFormat:tz')); } - let time = 1445027693942; + const time = 1445027693942; off = $scope.$on('change:config.dateFormat:tz', setDefaultTimezone); settings.set('dateFormat:tz', 'America/Chicago'); $scope.$digest(); - let chicagoTime = convert(time); + const chicagoTime = convert(time); settings.set('dateFormat:tz', 'America/Phoenix'); $scope.$digest(); - let phoenixTime = convert(time); + const phoenixTime = convert(time); expect(chicagoTime).not.to.equal(phoenixTime); off(); diff --git a/src/ui/public/stringify/__tests__/_source.js b/src/ui/public/stringify/__tests__/_source.js index 63d4691c33b09..38806c03dbed0 100644 --- a/src/ui/public/stringify/__tests__/_source.js +++ b/src/ui/public/stringify/__tests__/_source.js @@ -28,8 +28,8 @@ describe('_source formatting', function () { })); it('uses the _source, field, and hit to create a
', function () { - let hit = _.first(hits); - let $dl = $(convertHtml(hit._source, indexPattern.fields.byName._source, hit)); + const hit = _.first(hits); + const $dl = $(convertHtml(hit._source, indexPattern.fields.byName._source, hit)); expect($dl.is('dl')).to.be.ok(); expect($dl.find('dt')).to.have.length(_.keys(indexPattern.flattenHit(hit)).length); }); diff --git a/src/ui/public/stringify/__tests__/_string.js b/src/ui/public/stringify/__tests__/_string.js index f0b4b254db15e..19212e23b6670 100644 --- a/src/ui/public/stringify/__tests__/_string.js +++ b/src/ui/public/stringify/__tests__/_string.js @@ -10,16 +10,16 @@ describe('String Format', function () { })); it('decode a base64 string', function () { - let StringFormat = fieldFormats.getType('string'); - let string = new StringFormat({ + const StringFormat = fieldFormats.getType('string'); + const string = new StringFormat({ transform: 'base64' }); expect(string.convert('Zm9vYmFy')).to.be('foobar'); }); it('convert a string to title case', function () { - let StringFormat = fieldFormats.getType('string'); - let string = new StringFormat({ + const StringFormat = fieldFormats.getType('string'); + const string = new StringFormat({ transform: 'title' }); expect(string.convert('PLEASE DO NOT SHOUT')).to.be('Please Do Not Shout'); diff --git a/src/ui/public/stringify/__tests__/_truncate.js b/src/ui/public/stringify/__tests__/_truncate.js index 7e9564944402a..7f36690b8e1c7 100644 --- a/src/ui/public/stringify/__tests__/_truncate.js +++ b/src/ui/public/stringify/__tests__/_truncate.js @@ -10,29 +10,29 @@ describe('String Truncate Format', function () { })); it('truncate large string', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 4}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 4}); expect(truncate.convert('This is some text')).to.be('This...'); }); it('does not truncate large string when field length is not a string', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 'not number'}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 'not number'}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); it('does not truncate large string when field length is null', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: null}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: null}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); it('does not truncate large string when field length larger than the text', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 100000}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 100000}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); diff --git a/src/ui/public/stringify/__tests__/_url.js b/src/ui/public/stringify/__tests__/_url.js index 845ad0fb27885..48a918e67b867 100644 --- a/src/ui/public/stringify/__tests__/_url.js +++ b/src/ui/public/stringify/__tests__/_url.js @@ -19,9 +19,9 @@ describe('Url Format', function () { }); it('ouputs a simple tab by default', function () { - let url = new Url(); + const url = new Url(); - let $a = $(url.convert('http://elastic.co', 'html')); + const $a = $(url.convert('http://elastic.co', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('http://elastic.co'); @@ -30,17 +30,17 @@ describe('Url Format', function () { }); it('outputs an if type === "img"', function () { - let url = new Url({ type: 'img' }); + const url = new Url({ type: 'img' }); - let $img = $(url.convert('http://elastic.co', 'html')); + const $img = $(url.convert('http://elastic.co', 'html')); expect($img.is('img')).to.be(true); expect($img.attr('src')).to.be('http://elastic.co'); }); describe('url template', function () { it('accepts a template', function () { - let url = new Url({ urlTemplate: 'url: {{ value }}' }); - let $a = $(url.convert('url', 'html')); + const url = new Url({ urlTemplate: 'url: {{ value }}' }); + const $a = $(url.convert('url', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('url: url'); @@ -49,15 +49,15 @@ describe('Url Format', function () { }); it('only outputs the url if the contentType === "text"', function () { - let url = new Url(); + const url = new Url(); expect(url.convert('url', 'text')).to.be('url'); }); }); describe('label template', function () { it('accepts a template', function () { - let url = new Url({ labelTemplate: 'extension: {{ value }}' }); - let $a = $(url.convert('php', 'html')); + const url = new Url({ labelTemplate: 'extension: {{ value }}' }); + const $a = $(url.convert('php', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('php'); @@ -65,19 +65,19 @@ describe('Url Format', function () { }); it('uses the label template for text formating', function () { - let url = new Url({ labelTemplate: 'external {{value }}'}); + const url = new Url({ labelTemplate: 'external {{value }}'}); expect(url.convert('url', 'text')).to.be('external url'); }); it('can use the raw value', function () { - let url = new Url({ + const url = new Url({ labelTemplate: 'external {{value}}' }); expect(url.convert('url?', 'text')).to.be('external url?'); }); it('can use the url', function () { - let url = new Url({ + const url = new Url({ urlTemplate: 'http://google.com/{{value}}', labelTemplate: 'external {{url}}' }); @@ -87,19 +87,19 @@ describe('Url Format', function () { describe('templating', function () { it('ignores unknown variables', function () { - let url = new Url({ urlTemplate: '{{ not really a var }}' }); + const url = new Url({ urlTemplate: '{{ not really a var }}' }); expect(url.convert('url', 'text')).to.be(''); }); it('does not allow executing code in variable expressions', function () { window.SHOULD_NOT_BE_TRUE = false; - let url = new Url({ urlTemplate: '{{ (window.SHOULD_NOT_BE_TRUE = true) && value }}' }); + const url = new Url({ urlTemplate: '{{ (window.SHOULD_NOT_BE_TRUE = true) && value }}' }); expect(url.convert('url', 'text')).to.be(''); }); describe('', function () { it('does not get values from the prototype chain', function () { - let url = new Url({ urlTemplate: '{{ toString }}' }); + const url = new Url({ urlTemplate: '{{ toString }}' }); expect(url.convert('url', 'text')).to.be(''); }); }); diff --git a/src/ui/public/stringify/types/_numeral.js b/src/ui/public/stringify/types/_numeral.js index ee55f155b4341..9bbab9715436e 100644 --- a/src/ui/public/stringify/types/_numeral.js +++ b/src/ui/public/stringify/types/_numeral.js @@ -3,9 +3,9 @@ import 'ui/field_format_editor/numeral/numeral'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; export default function AbstractNumeralFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let BoundToConfigObj = Private(BoundToConfigObjProvider); - let numeral = require('numeral')(); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); + const numeral = require('numeral')(); _.class(Numeral).inherits(FieldFormat); function Numeral(params) { diff --git a/src/ui/public/stringify/types/boolean.js b/src/ui/public/stringify/types/boolean.js index 651b129ad0783..6c522db02527c 100644 --- a/src/ui/public/stringify/types/boolean.js +++ b/src/ui/public/stringify/types/boolean.js @@ -3,7 +3,7 @@ import _ from 'lodash'; export default function TruncateFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); class Bool extends FieldFormat { diff --git a/src/ui/public/stringify/types/bytes.js b/src/ui/public/stringify/types/bytes.js index 88e72823a4a4c..a585656df150b 100644 --- a/src/ui/public/stringify/types/bytes.js +++ b/src/ui/public/stringify/types/bytes.js @@ -1,7 +1,7 @@ import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function BytesFormatProvider(Private) { - let Numeral = Private(StringifyTypesNumeralProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'bytes', title: 'Bytes', diff --git a/src/ui/public/stringify/types/date.js b/src/ui/public/stringify/types/date.js index d88ff3ed4d910..b0faef57501a0 100644 --- a/src/ui/public/stringify/types/date.js +++ b/src/ui/public/stringify/types/date.js @@ -5,8 +5,8 @@ import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/fi import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; import dateTemplate from 'ui/stringify/editors/date.html'; export default function DateTimeFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let BoundToConfigObj = Private(BoundToConfigObjProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); _.class(DateTime).inherits(FieldFormat); @@ -27,7 +27,7 @@ export default function DateTimeFormatProvider(Private) { template: dateTemplate, controllerAs: 'cntrl', controller: function ($interval, $scope) { - let self = this; + const self = this; self.sampleInputs = [ Date.now(), +moment().startOf('year'), @@ -43,11 +43,11 @@ export default function DateTimeFormatProvider(Private) { DateTime.prototype._convert = function (val) { // don't give away our ref to converter so // we can hot-swap when config changes - let pattern = this.param('pattern'); - let timezone = this.param('timezone'); + const pattern = this.param('pattern'); + const timezone = this.param('timezone'); - let timezoneChanged = this._timeZone !== timezone; - let datePatternChanged = this._memoizedPattern !== pattern; + const timezoneChanged = this._timeZone !== timezone; + const datePatternChanged = this._memoizedPattern !== pattern; if (timezoneChanged || datePatternChanged) { this._timeZone = timezone; this._memoizedPattern = pattern; diff --git a/src/ui/public/stringify/types/ip.js b/src/ui/public/stringify/types/ip.js index 465d77fc3b41e..875c20401afc5 100644 --- a/src/ui/public/stringify/types/ip.js +++ b/src/ui/public/stringify/types/ip.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function IpFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(Ip).inherits(FieldFormat); function Ip(params) { diff --git a/src/ui/public/stringify/types/number.js b/src/ui/public/stringify/types/number.js index e9d12b1d241f2..569be5cf32bc4 100644 --- a/src/ui/public/stringify/types/number.js +++ b/src/ui/public/stringify/types/number.js @@ -1,7 +1,7 @@ import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function NumberFormatProvider(Private) { - let Numeral = Private(StringifyTypesNumeralProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'number', title: 'Number', diff --git a/src/ui/public/stringify/types/percent.js b/src/ui/public/stringify/types/percent.js index f309604ef0f0b..d4a2d672a0829 100644 --- a/src/ui/public/stringify/types/percent.js +++ b/src/ui/public/stringify/types/percent.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function PercentFormatProvider(Private) { - let BoundToConfigObj = Private(BoundToConfigObjProvider); - let Numeral = Private(StringifyTypesNumeralProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'percent', diff --git a/src/ui/public/stringify/types/source.js b/src/ui/public/stringify/types/source.js index 9662bfebef4ec..55fcde64cb491 100644 --- a/src/ui/public/stringify/types/source.js +++ b/src/ui/public/stringify/types/source.js @@ -3,8 +3,8 @@ import noWhiteSpace from 'ui/utils/no_white_space'; import angular from 'angular'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function _SourceFormatProvider(Private, shortDotsFilter) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let template = _.template(noWhiteSpace(require('ui/stringify/types/_source.html'))); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const template = _.template(noWhiteSpace(require('ui/stringify/types/_source.html'))); _.class(Source).inherits(FieldFormat); function Source(params) { @@ -20,15 +20,15 @@ export default function _SourceFormatProvider(Private, shortDotsFilter) { html: function sourceToHtml(source, field, hit) { if (!field) return this.getConverter('text')(source, field, hit); - let highlights = (hit && hit.highlight) || {}; - let formatted = field.indexPattern.formatHit(hit); - let highlightPairs = []; - let sourcePairs = []; + const highlights = (hit && hit.highlight) || {}; + const formatted = field.indexPattern.formatHit(hit); + const highlightPairs = []; + const sourcePairs = []; _.keys(formatted).forEach(function (key) { - let pairs = highlights[key] ? highlightPairs : sourcePairs; - let field = shortDotsFilter(key); - let val = formatted[key]; + const pairs = highlights[key] ? highlightPairs : sourcePairs; + const field = shortDotsFilter(key); + const val = formatted[key]; pairs.push([field, val]); }, []); diff --git a/src/ui/public/stringify/types/string.js b/src/ui/public/stringify/types/string.js index 3db37865534e7..259469706ab68 100644 --- a/src/ui/public/stringify/types/string.js +++ b/src/ui/public/stringify/types/string.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import 'ui/field_format_editor/samples/samples'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function StringFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(_String).inherits(FieldFormat); diff --git a/src/ui/public/stringify/types/truncate.js b/src/ui/public/stringify/types/truncate.js index 666add8819581..b20a7c2c62092 100644 --- a/src/ui/public/stringify/types/truncate.js +++ b/src/ui/public/stringify/types/truncate.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function TruncateFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let omission = '...'; + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const omission = '...'; _.class(Truncate).inherits(FieldFormat); @@ -16,7 +16,7 @@ export default function TruncateFormatProvider(Private) { Truncate.fieldType = ['string']; Truncate.prototype._convert = function (val) { - let length = this.param('fieldLength'); + const length = this.param('fieldLength'); if (length > 0) { return _.trunc(val, { 'length': length + omission.length, diff --git a/src/ui/public/stringify/types/url.js b/src/ui/public/stringify/types/url.js index eb1c46aeaaafe..a848567523ed9 100644 --- a/src/ui/public/stringify/types/url.js +++ b/src/ui/public/stringify/types/url.js @@ -5,7 +5,7 @@ import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/fi import urlTemplate from 'ui/stringify/editors/url.html'; export default function UrlFormatProvider(Private, highlightFilter) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(Url).inherits(FieldFormat); @@ -31,7 +31,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { template: urlTemplate, controllerAs: 'url', controller: function ($scope) { - let iconPattern = '/bundles/src/ui/public/stringify/icons/{{value}}.png'; + const iconPattern = '/bundles/src/ui/public/stringify/icons/{{value}}.png'; this.samples = { a: [ 'john', '/some/pathname/asset.png', 1234 ], @@ -39,7 +39,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; $scope.$watch('editor.formatParams.type', function (type, prev) { - let params = $scope.editor.formatParams; + const params = $scope.editor.formatParams; if (type === 'img' && type !== prev && !params.urlTemplate) { params.urlTemplate = iconPattern; } @@ -60,7 +60,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { ]; Url.prototype._formatUrl = function (value) { - let template = this.param('urlTemplate'); + const template = this.param('urlTemplate'); if (!template) return value; return this._compileTemplate(template)({ @@ -70,7 +70,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; Url.prototype._formatLabel = function (value, url) { - let template = this.param('labelTemplate'); + const template = this.param('labelTemplate'); if (url == null) url = this._formatUrl(value); if (!template) return url; @@ -86,7 +86,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }, html: function (rawValue, field, hit) { - let url = _.escape(this._formatUrl(rawValue)); + const url = _.escape(this._formatUrl(rawValue)); let label = _.escape(this._formatLabel(rawValue, url)); switch (this.param('type')) { @@ -103,7 +103,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; Url.prototype._compileTemplate = function (template) { - let parts = template.split(Url.templateMatchRE).map(function (part, i) { + const parts = template.split(Url.templateMatchRE).map(function (part, i) { // trim all the odd bits, the variable names return (i % 2) ? part.trim() : part; }); @@ -115,7 +115,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { while (++i < parts.length) { if (i % 2) { if (locals.hasOwnProperty(parts[i])) { - let local = locals[parts[i]]; + const local = locals[parts[i]]; output += local == null ? '' : local; } } else { diff --git a/src/ui/public/style_compile/__tests__/style_compile.js b/src/ui/public/style_compile/__tests__/style_compile.js index 3bb46d7f3cb27..804e0f0b59287 100644 --- a/src/ui/public/style_compile/__tests__/style_compile.js +++ b/src/ui/public/style_compile/__tests__/style_compile.js @@ -13,7 +13,7 @@ describe('styleCompile directive', function () { })); it('exports a few config values as css', function () { - let $style = $('#style-compile'); + const $style = $('#style-compile'); config.set('truncate:maxHeight', 0); $rootScope.$apply(); diff --git a/src/ui/public/style_compile/style_compile.js b/src/ui/public/style_compile/style_compile.js index 4ec2bd7367c03..90fc2e09fecbd 100644 --- a/src/ui/public/style_compile/style_compile.js +++ b/src/ui/public/style_compile/style_compile.js @@ -2,15 +2,15 @@ import _ from 'lodash'; import $ from 'jquery'; import 'ui/config'; import uiModules from 'ui/modules'; -let $style = $('