diff --git a/.eslintrc.js b/.eslintrc.js index a407a46c90755..59ae8c43e1d11 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -70,6 +70,7 @@ module.exports = { 'packages/kbn-test/**/*', 'packages/kbn-eslint-import-resolver-kibana/**/*', 'x-pack/plugins/apm/**/*', + 'x-pack/plugins/canvas/**/*', ], plugins: ['prettier'], rules: Object.assign( @@ -366,43 +367,30 @@ module.exports = { */ { files: ['x-pack/plugins/canvas/**/*'], - plugins: ['prettier'], rules: { - // preferences - 'comma-dangle': [2, 'always-multiline'], - 'no-multiple-empty-lines': [2, { max: 1, maxEOF: 1 }], - 'no-multi-spaces': 2, - radix: 2, - curly: [2, 'multi-or-nest', 'consistent'], - - // annoying rules that conflict with prettier - 'space-before-function-paren': 0, - indent: 0, - 'wrap-iife': 0, - 'max-len': 0, + radix: 'error', + curly: ['error', 'all'], // module importing 'import/order': [ - 2, - { groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'] }, + 'error', + { + groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'], + }, ], - 'import/extensions': [2, 'never', { json: 'always', less: 'always', svg: 'always' }], - - // prettier - 'prettier/prettier': 2, + 'import/extensions': ['error', 'never', { json: 'always', less: 'always', svg: 'always' }], // react - 'jsx-quotes': 2, - 'react/no-did-mount-set-state': 2, - 'react/no-did-update-set-state': 2, - 'react/no-multi-comp': [2, { ignoreStateless: true }], - 'react/self-closing-comp': 2, - 'react/sort-comp': 2, - 'react/jsx-boolean-value': 2, - 'react/jsx-wrap-multilines': 2, - 'react/no-unescaped-entities': [2, { forbid: ['>', '}'] }], + 'react/no-did-mount-set-state': 'error', + 'react/no-did-update-set-state': 'error', + 'react/no-multi-comp': ['error', { ignoreStateless: true }], + 'react/self-closing-comp': 'error', + 'react/sort-comp': 'error', + 'react/jsx-boolean-value': 'error', + 'react/jsx-wrap-multilines': 'error', + 'react/no-unescaped-entities': ['error', { forbid: ['>', '}'] }], 'react/forbid-elements': [ - 2, + 'error', { forbid: [ { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/sort.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/sort.js index 3cfaf7d46ae18..9940be856ec91 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/sort.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/sort.js @@ -13,7 +13,9 @@ describe('sort', () => { const fn = functionWrapper(sort); const isSorted = (rows, column, reverse) => { - if (reverse) return !rows.some((row, i) => rows[i + 1] && row[column] < rows[i + 1][column]); + if (reverse) { + return !rows.some((row, i) => rows[i + 1] && row[column] < rows[i + 1][column]); + } return !rows.some((row, i) => rows[i + 1] && row[column] > rows[i + 1][column]); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.js index c4e465b76c812..0c706e4d562bb 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.js @@ -32,18 +32,25 @@ export const alterColumn = () => ({ }, }, fn: (context, args) => { - if (!args.column || (!args.type && !args.name)) return context; + if (!args.column || (!args.type && !args.name)) { + return context; + } const column = context.columns.find(col => col.name === args.column); - if (!column) throw new Error(`Column not found: '${args.column}'`); + if (!column) { + throw new Error(`Column not found: '${args.column}'`); + } const name = args.name || column.name; const type = args.type || column.type; const columns = context.columns.reduce((all, col) => { if (col.name !== args.name) { - if (col.name !== column.name) all.push(col); - else all.push({ name, type }); + if (col.name !== column.name) { + all.push(col); + } else { + all.push({ name, type }); + } } return all; }, []); @@ -54,7 +61,9 @@ export const alterColumn = () => ({ handler = (function getHandler() { switch (type) { case 'string': - if (column.type === 'date') return v => new Date(v).toISOString(); + if (column.type === 'date') { + return v => new Date(v).toISOString(); + } return String; case 'number': return Number; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/axisConfig.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/axisConfig.js index 0d37c3b32c45f..a89f2206023ae 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/axisConfig.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/axisConfig.js @@ -42,7 +42,9 @@ export const axisConfig = () => ({ }, fn: (context, args) => { const positions = ['top', 'bottom', 'left', 'right', '']; - if (!positions.includes(args.position)) throw new Error(`Invalid position ${args.position}`); + if (!positions.includes(args.position)) { + throw new Error(`Invalid position ${args.position}`); + } const min = typeof args.min === 'string' ? moment.utc(args.min).valueOf() : args.min; const max = typeof args.max === 'string' ? moment.utc(args.max).valueOf() : args.max; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/case.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/case.js index b4579c414afce..026614cee2331 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/case.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/case.js @@ -33,12 +33,18 @@ export const caseFn = () => ({ }); async function doesMatch(context, args) { - if (typeof args.if !== 'undefined') return args.if; - if (typeof args.when !== 'undefined') return (await args.when()) === context; + if (typeof args.if !== 'undefined') { + return args.if; + } + if (typeof args.when !== 'undefined') { + return (await args.when()) === context; + } return true; } async function getResult(context, args) { - if (typeof args.then !== 'undefined') return await args.then(); + if (typeof args.then !== 'undefined') { + return await args.then(); + } return context; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.js index 1dba45a459471..a022ac707eb4a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.js @@ -46,7 +46,9 @@ export const columns = () => ({ const columns = []; fields.forEach(field => { const column = find(result.columns, { name: field }); - if (column) columns.push(column); + if (column) { + columns.push(column); + } }); const rows = columns.length > 0 ? result.rows.map(row => pick(row, fields)) : []; result = { ...result, rows, columns }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/compare.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/compare.js index c9dd2245b8696..a0c117af7dd8d 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/compare.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/compare.js @@ -41,16 +41,24 @@ export const compare = () => ({ case 'ne': return a !== b; case 'lt': - if (typesMatch) return a < b; + if (typesMatch) { + return a < b; + } return false; case 'lte': - if (typesMatch) return a <= b; + if (typesMatch) { + return a <= b; + } return false; case 'gt': - if (typesMatch) return a > b; + if (typesMatch) { + return a > b; + } return false; case 'gte': - if (typesMatch) return a >= b; + if (typesMatch) { + return a >= b; + } return false; default: throw new Error('Invalid compare operator. Use eq, ne, lt, gt, lte, or gte.'); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/containerStyle.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/containerStyle.js index a5e71e3143e16..8ff58b539d6d9 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/containerStyle.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/containerStyle.js @@ -67,8 +67,9 @@ export const containerStyle = () => ({ }; if (backgroundImage) { - if (!isValidUrl(backgroundImage)) + if (!isValidUrl(backgroundImage)) { throw new Error('Invalid backgroundImage. Please provide an asset or a URL.'); + } style.backgroundImage = `url(${backgroundImage})`; style.backgroundSize = backgroundSize; style.backgroundRepeat = backgroundRepeat; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.js index 4a02b901786c8..63df4fc6d06d6 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.js @@ -41,8 +41,12 @@ export const csv = () => ({ }, }; - if (delimiter != null) config.delimiter = delimiter; - if (newline != null) config.newline = newline; + if (delimiter != null) { + config.delimiter = delimiter; + } + if (newline != null) { + config.newline = newline; + } // TODO: handle errors, check output.errors const output = Papa.parse(csvString, config); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/date.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/date.js index 23b2631325763..ff17cf25518d1 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/date.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/date.js @@ -8,7 +8,9 @@ import moment from 'moment'; const getInputDate = input => { // return current date if no input - if (!input) return new Date(); + if (!input) { + return new Date(); + } // return the input return input; @@ -40,7 +42,9 @@ export const date = () => ({ const useMoment = date && format; const outputDate = useMoment ? moment.utc(date, format).toDate() : new Date(getInputDate(date)); - if (isNaN(outputDate.getTime())) throw new Error(`Invalid date input: ${date}`); + if (isNaN(outputDate.getTime())) { + throw new Error(`Invalid date input: ${date}`); + } return outputDate.valueOf(); }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.js index ebb94cde8fb68..dddec18e5a809 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.js @@ -26,8 +26,9 @@ export const dropdownControl = () => ({ }, fn: (context, { valueColumn, filterColumn }) => { let choices = []; - if (context.rows[0][valueColumn]) + if (context.rows[0][valueColumn]) { choices = uniq(context.rows.map(row => row[valueColumn])).sort(); + } const column = filterColumn || valueColumn; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/font.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/font.js index c8b0141d2ef24..ec99f19d8d598 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/font.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/font.js @@ -79,8 +79,12 @@ export const font = () => ({ }, }, fn: (context, args) => { - if (!weights.includes(args.weight)) throw new Error(`Invalid font weight: ${args.weight}`); - if (!alignments.includes(args.align)) throw new Error(`Invalid text alignment: ${args.align}`); + if (!weights.includes(args.weight)) { + throw new Error(`Invalid font weight: ${args.weight}`); + } + if (!alignments.includes(args.align)) { + throw new Error(`Invalid text alignment: ${args.align}`); + } // the line height shouldn't ever be lower than the size const lineHeight = args.lHeight ? `${args.lHeight}px` : 1; @@ -96,7 +100,9 @@ export const font = () => ({ }; // conditionally apply styles based on input - if (args.color) spec.color = args.color; + if (args.color) { + spec.color = args.color; + } return { type: 'style', diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatdate.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatdate.js index 489317928e035..5a33e750d5065 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatdate.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatdate.js @@ -20,7 +20,9 @@ export const formatdate = () => ({ }, }, fn: (context, args) => { - if (!args.format) return moment.utc(new Date(context)).toISOString(); + if (!args.format) { + return moment.utc(new Date(context)).toISOString(); + } return moment.utc(new Date(context)).format(args.format); }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatnumber.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatnumber.js index ff3cd5f243d46..a2f8546068f0f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatnumber.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/formatnumber.js @@ -21,7 +21,9 @@ export const formatnumber = () => ({ }, }, fn: (context, args) => { - if (!args.format) return String(context); + if (!args.format) { + return String(context); + } return numeral(context).format(args.format); }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/getCell.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/getCell.js index 625db0a434a4d..e978c6d64c9f8 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/getCell.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/getCell.js @@ -25,12 +25,16 @@ export const getCell = () => ({ }, fn: (context, args) => { const row = context.rows[args.row]; - if (!row) throw new Error(`Row not found: ${args.row}`); + if (!row) { + throw new Error(`Row not found: ${args.row}`); + } const { column = context.columns[0].name } = args; const value = row[column]; - if (typeof value === 'undefined') throw new Error(`Column not found: ${column}`); + if (typeof value === 'undefined') { + throw new Error(`Column not found: ${column}`); + } return value; }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gt.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gt.js index ccde455f20cba..5bde46008b43a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gt.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gt.js @@ -17,7 +17,9 @@ export const gt = () => ({ }, }, fn: (context, args) => { - if (typeof context !== typeof args.value) return false; + if (typeof context !== typeof args.value) { + return false; + } return context > args.value; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gte.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gte.js index 691deae146c05..e368560988eaf 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gte.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/gte.js @@ -17,7 +17,9 @@ export const gte = () => ({ }, }, fn: (context, args) => { - if (typeof context !== typeof args.value) return false; + if (typeof context !== typeof args.value) { + return false; + } return context >= args.value; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.js index fa54a14b0998a..1d67e6425851f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.js @@ -27,10 +27,14 @@ export const ifFn = () => ({ }, fn: async (context, args) => { if (args.condition) { - if (typeof args.then === 'undefined') return context; + if (typeof args.then === 'undefined') { + return context; + } return await args.then(); } else { - if (typeof args.else === 'undefined') return context; + if (typeof args.else === 'undefined') { + return context; + } return await args.else(); } }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/image.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/image.js index 5bf6c429331f7..577580eb3f41a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/image.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/image.js @@ -36,7 +36,9 @@ export const image = () => ({ }, }, fn: (context, { dataurl, mode }) => { - if (!modes.includes(mode)) throw '"mode" must be "contain", "cover", or "stretch"'; + if (!modes.includes(mode)) { + throw '"mode" must be "contain", "cover", or "stretch"'; + } const modeStyle = mode === 'stretch' ? '100% 100%' : mode; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lt.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lt.js index f2d90639fc995..a7c87657deb4f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lt.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lt.js @@ -17,7 +17,9 @@ export const lt = () => ({ }, }, fn: (context, args) => { - if (typeof context !== typeof args.value) return false; + if (typeof context !== typeof args.value) { + return false; + } return context < args.value; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lte.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lte.js index ed9a413a71ede..98822ed2235e8 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lte.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/lte.js @@ -17,7 +17,9 @@ export const lte = () => ({ }, }, fn: (context, args) => { - if (typeof context !== typeof args.value) return false; + if (typeof context !== typeof args.value) { + return false; + } return context <= args.value; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.js index 825744858527f..a909aca0bda2f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.js @@ -49,8 +49,11 @@ export const mapColumn = () => ({ const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); const type = getType(rows[0][args.name]); const newColumn = { name: args.name, type }; - if (existingColumnIndex === -1) columns.push(newColumn); - else columns[existingColumnIndex] = newColumn; + if (existingColumnIndex === -1) { + columns.push(newColumn); + } else { + columns[existingColumnIndex] = newColumn; + } return { type: 'datatable', diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.js index ded8500ffbb09..132e35be043d3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.js @@ -25,7 +25,9 @@ export const math = () => ({ }, }, fn: (context, args) => { - if (!args.expression || args.expression.trim() === '') throw new Error('Empty expression'); + if (!args.expression || args.expression.trim() === '') { + throw new Error('Empty expression'); + } const isDatatable = context && context.type === 'datatable'; const mathContext = isDatatable @@ -34,17 +36,23 @@ export const math = () => ({ try { const result = evaluate(args.expression, mathContext); if (Array.isArray(result)) { - if (result.length === 1) return result[0]; + if (result.length === 1) { + return result[0]; + } throw new Error( 'Expressions must return a single number. Try wrapping your expression in mean() or sum()' ); } - if (isNaN(result)) + if (isNaN(result)) { throw new Error('Failed to execute math expression. Check your column names'); + } return result; } catch (e) { - if (context.rows.length === 0) throw new Error('Empty datatable'); - else throw e; + if (context.rows.length === 0) { + throw new Error('Empty datatable'); + } else { + throw e; + } } }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.js index 2cc0fbaeb30c0..bc206e3fb0c2b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.js @@ -79,7 +79,9 @@ export const pie = () => ({ const seriesStyle = seriesStyles[label]; // append series style, if there is a match - if (seriesStyle) item.color = get(seriesStyle, 'color'); + if (seriesStyle) { + item.color = get(seriesStyle, 'color'); + } return item; }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_flot_axis_config.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_flot_axis_config.js index 6391b01c3ded6..ea426abff8e5b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_flot_axis_config.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_flot_axis_config.js @@ -8,7 +8,9 @@ import { get, map } from 'lodash'; import { getType } from '@kbn/interpreter/common'; export const getFlotAxisConfig = (axis, argValue, { columns, ticks, font } = {}) => { - if (!argValue || argValue.show === false) return { show: false }; + if (!argValue || argValue.show === false) { + return { show: false }; + } const config = { show: true }; const axisType = get(columns, `${axis}.type`); @@ -21,19 +23,30 @@ export const getFlotAxisConfig = (axis, argValue, { columns, ticks, font } = {}) config.position = acceptedPositions.includes(position) ? position : acceptedPositions[0]; if (axisType === 'number' || axisType === 'date') { - if (min) config.min = min; - if (max) config.max = max; + if (min) { + config.min = min; + } + if (max) { + config.max = max; + } } - if (tickSize && axisType === 'number') config.tickSize = tickSize; + if (tickSize && axisType === 'number') { + config.tickSize = tickSize; + } } - if (axisType === 'string') + if (axisType === 'string') { config.ticks = map(ticks[axis].hash, (position, name) => [position, name]); + } - if (axisType === 'date') config.mode = 'time'; + if (axisType === 'date') { + config.mode = 'time'; + } - if (typeof font === 'object') config.font = font; + if (typeof font === 'object') { + config.font = font; + } return config; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_font_spec.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_font_spec.js index 1d9242833b646..7532a6ac840f9 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_font_spec.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_font_spec.js @@ -17,7 +17,9 @@ export const defaultSpec = { }; export const getFontSpec = argFont => { - if (!argFont || !argFont.spec) return defaultSpec; + if (!argFont || !argFont.spec) { + return defaultSpec; + } const { fontSize, lineHeight, fontStyle, fontWeight, fontFamily, color } = argFont.spec; const size = fontSize && Number(fontSize.replace('px', '')); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.js index 6ca670b881303..0e7f8306e48e3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.js @@ -20,7 +20,9 @@ export const getTickHash = (columns, rows) => { if (get(columns, 'x.type') === 'string') { sortBy(rows, ['x']).forEach(row => { - if (!ticks.x.hash[row.x]) ticks.x.hash[row.x] = ticks.x.counter++; + if (!ticks.x.hash[row.x]) { + ticks.x.hash[row.x] = ticks.x.counter++; + } }); } @@ -28,7 +30,9 @@ export const getTickHash = (columns, rows) => { sortBy(rows, ['y']) .reverse() .forEach(row => { - if (!ticks.y.hash[row.y]) ticks.y.hash[row.y] = ticks.y.counter++; + if (!ticks.y.hash[row.y]) { + ticks.y.hash[row.y] = ticks.y.counter++; + } }); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.js index c76a7d658da09..4b00d4c399323 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.js @@ -88,7 +88,9 @@ export const plot = () => ({ set(flotStyle, 'bubbles.size.min', seriesStyle.points); } - if (point.text != null) attrs.text = point.text; + if (point.text != null) { + attrs.text = point.text; + } return [x, y, attrs]; }), diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/series_style_to_flot.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/series_style_to_flot.js index 644487e4ac71e..1b187c8e44ca6 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/series_style_to_flot.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/series_style_to_flot.js @@ -7,7 +7,9 @@ import { get } from 'lodash'; export const seriesStyleToFlot = seriesStyle => { - if (!seriesStyle) return {}; + if (!seriesStyle) { + return {}; + } const lines = get(seriesStyle, 'lines'); const bars = get(seriesStyle, 'bars'); @@ -42,8 +44,12 @@ export const seriesStyleToFlot = seriesStyle => { }, }; - if (stack) flotStyle.stack = stack; - if (color) flotStyle.color = color; + if (stack) { + flotStyle.stack = stack; + } + if (color) { + flotStyle.color = color; + } return flotStyle; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.js index f3f167275949f..c082c5c4c988d 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.js @@ -10,8 +10,11 @@ function combineColumns(arrayOfColumnsArrays) { return arrayOfColumnsArrays.reduce((resultingColumns, columns) => { if (columns) { columns.forEach(column => { - if (resultingColumns.find(resultingColumn => resultingColumn.name === column.name)) return; - else resultingColumns.push(column); + if (resultingColumns.find(resultingColumn => resultingColumn.name === column.name)) { + return; + } else { + resultingColumns.push(column); + } }); } @@ -27,8 +30,9 @@ function combineAcross(datatableArray) { // Sanity check datatableArray.forEach(datatable => { - if (datatable.rows.length !== targetRowLength) + if (datatable.rows.length !== targetRowLength) { throw new Error('All expressions must return the same number of rows'); + } }); // Merge columns and rows. @@ -81,14 +85,18 @@ export const ply = () => ({ // The way the function below is written you can add as many arbitrary named args as you want. }, fn: (context, args) => { - if (!args) return context; + if (!args) { + return context; + } let byColumns; let originalDatatables; if (args.by) { byColumns = args.by.map(by => { const column = context.columns.find(column => column.name === by); - if (!column) throw new Error(`No such column: ${by}`); + if (!column) { + throw new Error(`No such column: ${by}`); + } return column; }); const keyedDatatables = groupBy(context.rows, row => JSON.stringify(pick(row, args.by))); @@ -103,9 +111,11 @@ export const ply = () => ({ const datatablePromises = originalDatatables.map(originalDatatable => { let expressionResultPromises = []; - if (args.expression) + if (args.expression) { expressionResultPromises = args.expression.map(expression => expression(originalDatatable)); - else expressionResultPromises.push(Promise.resolve(originalDatatable)); + } else { + expressionResultPromises.push(Promise.resolve(originalDatatable)); + } return Promise.all(expressionResultPromises).then(combineAcross); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/progress.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/progress.js index 453730b3f861a..863e606984f74 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/progress.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/progress.js @@ -71,11 +71,17 @@ export const progress = () => ({ }, }, fn: (value, args) => { - if (args.max <= 0) throw new Error(`'max' must be greater than 0`); - if (value > args.max || value < 0) throw new Error(`Context must be between 0 and ${args.max}`); + if (args.max <= 0) { + throw new Error(`'max' must be greater than 0`); + } + if (value > args.max || value < 0) { + throw new Error(`Context must be between 0 and ${args.max}`); + } let label = ''; - if (args.label) label = typeof args.label === 'string' ? args.label : `${value}`; + if (args.label) { + label = typeof args.label === 'string' ? args.label : `${value}`; + } let font = {}; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/revealImage.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/revealImage.js index 9d54dc9363b95..888f0899978da 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/revealImage.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/revealImage.js @@ -34,7 +34,9 @@ export const revealImage = () => ({ }, }, fn: (percent, args) => { - if (percent > 1 || percent < 0) throw new Error('input must be between 0 and 1'); + if (percent > 1 || percent < 0) { + throw new Error('input must be between 0 and 1'); + } return { type: 'render', diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rounddate.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rounddate.js index 1eeccd1b19432..e5b95d881878c 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rounddate.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rounddate.js @@ -22,7 +22,9 @@ export const rounddate = () => ({ }, }, fn: (context, args) => { - if (!args.format) return context; + if (!args.format) { + return context; + } return moment.utc(moment.utc(context).format(args.format), args.format).valueOf(); }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.js index 4a5d06ac8c170..648d6860e04b8 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.js @@ -34,8 +34,11 @@ export const staticColumn = () => ({ const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); const newColumn = { name: args.name, type }; - if (existingColumnIndex > -1) columns[existingColumnIndex] = newColumn; - else columns.push(newColumn); + if (existingColumnIndex > -1) { + columns[existingColumnIndex] = newColumn; + } else { + columns.push(newColumn); + } return { type: 'datatable', diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.js index 3cb3577cf74c8..1e3ef069c8c6b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.js @@ -25,9 +25,13 @@ export const switchFn = () => ({ const cases = args.case || []; for (let i = 0; i < cases.length; i++) { const { matches, result } = await cases[i](); - if (matches) return result; + if (matches) { + return result; + } + } + if (typeof args.default !== 'undefined') { + return await args.default(); } - if (typeof args.default !== 'undefined') return await args.default(); return context; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.js index 42463bf374e65..f9a8b12497ac1 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.js @@ -33,7 +33,9 @@ export const timefilter = () => ({ }, }, fn: (context, args) => { - if (!args.from && !args.to) return context; + if (!args.from && !args.to) { + return context; + } const { from, to, column } = args; const filter = { @@ -42,16 +44,24 @@ export const timefilter = () => ({ }; function parseAndValidate(str) { - if (!str) return; + if (!str) { + return; + } const moment = dateMath.parse(str); - if (!moment || !moment.isValid()) throw new Error(`Invalid date/time string ${str}`); + if (!moment || !moment.isValid()) { + throw new Error(`Invalid date/time string ${str}`); + } return moment.toISOString(); } - if (to != null) filter.to = parseAndValidate(to); + if (to != null) { + filter.to = parseAndValidate(to); + } - if (from != null) filter.from = parseAndValidate(from); + if (from != null) { + filter.from = parseAndValidate(from); + } return { ...context, and: [...context.and, filter] }; }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/demodata/get_demo_rows.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/demodata/get_demo_rows.js index 16077d9b69efa..78bb441e242cb 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/demodata/get_demo_rows.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/demodata/get_demo_rows.js @@ -9,7 +9,11 @@ import ci from './ci.json'; import shirts from './shirts.json'; export function getDemoRows(arg) { - if (arg === 'ci') return cloneDeep(ci); - if (arg === 'shirts') return cloneDeep(shirts); + if (arg === 'ci') { + return cloneDeep(ci); + } + if (arg === 'shirts') { + return cloneDeep(shirts); + } throw new Error(`Invalid data set: ${arg}, use 'ci' or 'shirts'.`); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/esdocs.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/esdocs.js index a70d0361907ba..8ef3d517227e7 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/esdocs.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/esdocs.js @@ -70,7 +70,9 @@ export const esdocs = () => ({ if (args.sort) { const [sortField, sortOrder] = args.sort.split(',').map(str => str.trim()); - if (sortField) query.order(`"${sortField}"`, sortOrder.toLowerCase() === 'asc'); + if (sortField) { + query.order(`"${sortField}"`, sortOrder.toLowerCase() === 'asc'); + } } return queryEsSQL(handlers.elasticsearchClient, { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/index.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/index.js index 02fc450f32eca..02f927f8f7902 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/index.js @@ -56,7 +56,9 @@ export const pointseries = () => ({ const columnNames = context.columns.map(col => col.name); const mathScope = pivotObjectArray(context.rows, columnNames); const autoQuoteColumn = col => { - if (!columnNames.includes(col)) return col; + if (!columnNames.includes(col)) { + return col; + } return col.match(/\s/) ? `'${col}'` : col; }; @@ -78,7 +80,9 @@ export const pointseries = () => ({ if (isColumnReference(mathExp)) { // TODO: Do something better if the column does not exist - if (!columnExists(columnNames, mathExp)) return; + if (!columnExists(columnNames, mathExp)) { + return; + } dimensions.push({ name: arg, @@ -147,8 +151,9 @@ export const pointseries = () => ({ const measureValues = measureNames.map(measure => { try { const ev = evaluate(args[measure], subScope); - if (Array.isArray(ev)) + if (Array.isArray(ev)) { throw new Error('Expressions must be wrapped in a function such as sum()'); + } return ev; } catch (e) { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_expression_type.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_expression_type.js index 4da10af4dd11b..98b4b0ae788e7 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_expression_type.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_expression_type.js @@ -12,7 +12,9 @@ import { getFieldNames } from './get_field_names'; export function getExpressionType(columns, mathExpression) { // if isColumnReference returns true, then mathExpression is just a string // referencing a column in a datatable - if (isColumnReference(mathExpression)) return getFieldType(columns, mathExpression); + if (isColumnReference(mathExpression)) { + return getFieldType(columns, mathExpression); + } const parsedMath = parse(mathExpression); @@ -22,7 +24,9 @@ export function getExpressionType(columns, mathExpression) { if (fieldNames.length > 0) { const fieldTypes = fieldNames.reduce((types, name) => { const type = getFieldType(columns, name); - if (type !== 'null' && types.indexOf(type) === -1) return types.concat(type); + if (type !== 'null' && types.indexOf(type) === -1) { + return types.concat(type); + } return types; }, []); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_field_names.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_field_names.js index 835138477fcf7..2f47d84d6d6ee 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_field_names.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/get_field_names.js @@ -5,9 +5,13 @@ */ export function getFieldNames(names, arg) { - if (arg.args != null) return names.concat(arg.args.reduce(getFieldNames, [])); + if (arg.args != null) { + return names.concat(arg.args.reduce(getFieldNames, [])); + } - if (typeof arg === 'string') return names.concat(arg); + if (typeof arg === 'string') { + return names.concat(arg); + } return names; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/is_column_reference.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/is_column_reference.js index 3d66bd9a97c2a..3163fae377351 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/is_column_reference.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/src/pointseries/lib/is_column_reference.js @@ -7,7 +7,9 @@ import { parse } from 'tinymath'; export function isColumnReference(mathExpression) { - if (mathExpression == null) mathExpression = 'null'; + if (mathExpression == null) { + mathExpression = 'null'; + } const parsedMath = parse(mathExpression); return typeof parsedMath === 'string'; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/index.js index 7d007d70b6bab..b60d341b75552 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/index.js @@ -17,7 +17,9 @@ export const pie = () => ({ help: 'Render a pie chart from data', reuseDomNode: false, render(domNode, config, handlers) { - if (!includes($.plot.plugins, piePlugin)) $.plot.plugins.push(piePlugin); + if (!includes($.plot.plugins, piePlugin)) { + $.plot.plugins.push(piePlugin); + } config.options.legend.labelBoxBorderColor = 'transparent'; @@ -49,12 +51,17 @@ export const pie = () => ({ let plot; function draw() { - if (domNode.clientHeight < 1 || domNode.clientWidth < 1) return; + if (domNode.clientHeight < 1 || domNode.clientWidth < 1) { + return; + } try { $(domNode).empty(); - if (!config.data || !config.data.length) $(domNode).empty(); - else plot = $.plot($(domNode), config.data, config.options); + if (!config.data || !config.data.length) { + $(domNode).empty(); + } else { + plot = $.plot($(domNode), config.data, config.options); + } } catch (e) { console.log(e); // Nope @@ -62,7 +69,9 @@ export const pie = () => ({ } function destroy() { - if (plot) plot.shutdown(); + if (plot) { + plot.shutdown(); + } } handlers.onDestroy(destroy); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js index 4e6616a625023..9229def146f8b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js @@ -96,46 +96,65 @@ function init(plot) { // set labels.show if (options.series.pie.label.show === 'auto') { - if (options.legend.show) options.series.pie.label.show = false; - else options.series.pie.label.show = true; + if (options.legend.show) { + options.series.pie.label.show = false; + } else { + options.series.pie.label.show = true; + } } // set radius if (options.series.pie.radius === 'auto') { - if (options.series.pie.label.show) options.series.pie.radius = 3 / 4; - else options.series.pie.radius = 1; + if (options.series.pie.label.show) { + options.series.pie.radius = 3 / 4; + } else { + options.series.pie.radius = 1; + } } // ensure sane tilt - if (options.series.pie.tilt > 1) options.series.pie.tilt = 1; - else if (options.series.pie.tilt < 0) options.series.pie.tilt = 0; + if (options.series.pie.tilt > 1) { + options.series.pie.tilt = 1; + } else if (options.series.pie.tilt < 0) { + options.series.pie.tilt = 0; + } } }); plot.hooks.bindEvents.push(function(plot, eventHolder) { const options = plot.getOptions(); if (options.series.pie.show) { - if (options.grid.hoverable) eventHolder.unbind('mousemove').mousemove(onMouseMove); + if (options.grid.hoverable) { + eventHolder.unbind('mousemove').mousemove(onMouseMove); + } - if (options.grid.clickable) eventHolder.unbind('click').click(onClick); + if (options.grid.clickable) { + eventHolder.unbind('click').click(onClick); + } } }); plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { const options = plot.getOptions(); - if (options.series.pie.show) processDatapoints(plot, series, data, datapoints); + if (options.series.pie.show) { + processDatapoints(plot, series, data, datapoints); + } }); plot.hooks.drawOverlay.push(function(plot, octx) { const options = plot.getOptions(); - if (options.series.pie.show) drawOverlay(plot, octx); + if (options.series.pie.show) { + drawOverlay(plot, octx); + } }); plot.hooks.draw.push(function(plot, newCtx) { const options = plot.getOptions(); - if (options.series.pie.show) draw(plot, newCtx); + if (options.series.pie.show) { + draw(plot, newCtx); + } }); function processDatapoints(plot) { @@ -167,12 +186,17 @@ function init(plot) { // new one; this is more efficient and preserves any extra data // that the user may have stored in higher indexes. - if (Array.isArray(value) && value.length === 1) value = value[0]; + if (Array.isArray(value) && value.length === 1) { + value = value[0]; + } if (Array.isArray(value)) { // Equivalent to $.isNumeric() but compatible with jQuery < 1.7 - if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) value[1] = +value[1]; - else value[1] = 0; + if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) { + value[1] = +value[1]; + } else { + value[1] = 0; + } } else if (!isNaN(parseFloat(value)) && isFinite(value)) { value = [1, +value]; } else { @@ -184,7 +208,9 @@ function init(plot) { // Sum up all the slices, so we can calculate percentages for each - for (let i = 0; i < data.length; ++i) total += data[i].data[0][1]; + for (let i = 0; i < data.length; ++i) { + total += data[i].data[0][1]; + } // Count the number of slices with percentages below the combine // threshold; if it turns out to be just one, we won't combine. @@ -194,7 +220,9 @@ function init(plot) { if (value / total <= options.series.pie.combine.threshold) { combined += value; numCombined++; - if (!color) color = data[i].color; + if (!color) { + color = data[i].color; + } } } @@ -229,7 +257,9 @@ function init(plot) { } function draw(plot, newCtx) { - if (!target) return; // if no series were passed + if (!target) { + return; + } // if no series were passed const canvasWidth = plot.getPlaceholder().width(); const canvasHeight = plot.getPlaceholder().height(); @@ -272,11 +302,17 @@ function init(plot) { centerLeft = canvasWidth / 2; if (options.series.pie.offset.left === 'auto') { - if (options.legend.position.match('w')) centerLeft += legendWidth / 2; - else centerLeft -= legendWidth / 2; + if (options.legend.position.match('w')) { + centerLeft += legendWidth / 2; + } else { + centerLeft -= legendWidth / 2; + } - if (centerLeft < maxRadius) centerLeft = maxRadius; - else if (centerLeft > canvasWidth - maxRadius) centerLeft = canvasWidth - maxRadius; + if (centerLeft < maxRadius) { + centerLeft = maxRadius; + } else if (centerLeft > canvasWidth - maxRadius) { + centerLeft = canvasWidth - maxRadius; + } } else { centerLeft += options.series.pie.offset.left; } @@ -288,11 +324,15 @@ function init(plot) { // indicating that all the labels fit, or we try too many times. do { - if (attempts > 0) maxRadius *= REDRAW_SHRINK; + if (attempts > 0) { + maxRadius *= REDRAW_SHRINK; + } attempts += 1; clear(); - if (options.series.pie.tilt <= 0.8) drawShadow(); + if (options.series.pie.tilt <= 0.8) { + drawShadow(); + } } while (!drawPie() && attempts < REDRAW_ATTEMPTS); if (attempts >= REDRAW_ATTEMPTS) { @@ -331,8 +371,9 @@ function init(plot) { radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge - ) - return; // shadow would be outside canvas, so don't draw it + ) { + return; + } // shadow would be outside canvas, so don't draw it ctx.save(); ctx.translate(shadowLeft, shadowTop); @@ -386,8 +427,9 @@ function init(plot) { ctx.save(); ctx.lineWidth = options.series.pie.stroke.width; currentAngle = startAngle; - for (let i = 0; i < slices.length; ++i) + for (let i = 0; i < slices.length; ++i) { drawSlice(slices[i].angle, options.series.pie.stroke.color, false); + } ctx.restore(); } @@ -400,11 +442,16 @@ function init(plot) { // Draw the labels, returning true if they fit within the plot - if (options.series.pie.label.show) return drawLabels(); - else return true; + if (options.series.pie.label.show) { + return drawLabels(); + } else { + return true; + } function drawSlice(angle, color, fill) { - if (angle <= 0 || isNaN(angle)) return; + if (angle <= 0 || isNaN(angle)) { + return; + } if (fill) { ctx.fillStyle = color; @@ -414,7 +461,9 @@ function init(plot) { } ctx.beginPath(); - if (Math.abs(angle - Math.PI * 2) > 0.000000001) ctx.moveTo(0, 0); // Center of the pie + if (Math.abs(angle - Math.PI * 2) > 0.000000001) { + ctx.moveTo(0, 0); + } // Center of the pie //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera ctx.arc(0, 0, radius, currentAngle, currentAngle + angle / 2, false); @@ -423,8 +472,11 @@ function init(plot) { //ctx.rotate(angle); // This doesn't work properly in Opera currentAngle += angle; - if (fill) ctx.fill(); - else ctx.stroke(); + if (fill) { + ctx.fill(); + } else { + ctx.stroke(); + } } function drawLabels() { @@ -435,8 +487,11 @@ function init(plot) { : maxRadius * options.series.pie.label.radius; for (let i = 0; i < slices.length; ++i) { - if (slices[i].percent >= options.series.pie.label.threshold * 100) - if (!drawLabel(slices[i], currentAngle, i)) return false; + if (slices[i].percent >= options.series.pie.label.threshold * 100) { + if (!drawLabel(slices[i], currentAngle, i)) { + return false; + } + } currentAngle += slices[i].angle; } @@ -444,7 +499,9 @@ function init(plot) { return true; function drawLabel(slice, startAngle, index) { - if (slice.data[0][1] === 0) return true; + if (slice.data[0][1] === 0) { + return true; + } // format label text @@ -452,10 +509,15 @@ function init(plot) { let text; const plf = options.series.pie.label.formatter; - if (lf) text = lf(slice.label, slice); - else text = slice.label; + if (lf) { + text = lf(slice.label, slice); + } else { + text = slice.label; + } - if (plf) text = plf(text, slice); + if (plf) { + text = plf(text, slice); + } const halfAngle = (startAngle + slice.angle + startAngle) / 2; const x = centerLeft + Math.round(Math.cos(halfAngle) * radius); @@ -487,15 +549,18 @@ function init(plot) { 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0 - ) + ) { return false; + } if (options.series.pie.label.background.opacity !== 0) { // put in the transparent background separately to avoid blended labels and label boxes let c = options.series.pie.label.background.color; - if (c == null) c = slice.color; + if (c == null) { + c = slice.color; + } const pos = 'top:' + labelTop + 'px;left:' + labelLeft + 'px;'; $( @@ -662,13 +727,17 @@ function init(plot) { for (let i = 0; i < highlights.length; ++i) { const h = highlights[i]; - if (h.auto === eventname && !(item && h.series === item.series)) unhighlight(h.series); + if (h.auto === eventname && !(item && h.series === item.series)) { + unhighlight(h.series); + } } } // highlight the slice - if (item) highlight(item.series, eventname); + if (item) { + highlight(item.series, eventname); + } // trigger any hover bind events @@ -712,7 +781,9 @@ function init(plot) { function indexOfHighlight(s) { for (let i = 0; i < highlights.length; ++i) { const h = highlights[i]; - if (h.series === s) return i; + if (h.series === s) { + return i; + } } return -1; } @@ -729,19 +800,25 @@ function init(plot) { octx.translate(centerLeft, centerTop); octx.scale(1, options.series.pie.tilt); - for (let i = 0; i < highlights.length; ++i) drawHighlight(highlights[i].series); + for (let i = 0; i < highlights.length; ++i) { + drawHighlight(highlights[i].series); + } drawDonutHole(octx); octx.restore(); function drawHighlight(series) { - if (series.angle <= 0 || isNaN(series.angle)) return; + if (series.angle <= 0 || isNaN(series.angle)) { + return; + } //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); octx.fillStyle = 'rgba(255, 255, 255, ' + options.series.pie.highlight.opacity + ')'; // this is temporary until we have access to parseColor octx.beginPath(); - if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) octx.moveTo(0, 0); // Center of the pie + if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) { + octx.moveTo(0, 0); + } // Center of the pie octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false); octx.arc( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/index.js index 67f26abb1c6b8..9a2d0e4a9b26d 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/index.js @@ -15,12 +15,18 @@ import './plot.scss'; const render = (domNode, config, handlers) => { // TODO: OH NOES - if (!includes($.plot.plugins, size)) $.plot.plugins.push(size); - if (!includes($.plot.plugins, text)) $.plot.plugins.push(text); + if (!includes($.plot.plugins, size)) { + $.plot.plugins.push(size); + } + if (!includes($.plot.plugins, text)) { + $.plot.plugins.push(text); + } let plot; function draw() { - if (domNode.clientHeight < 1 || domNode.clientWidth < 1) return; + if (domNode.clientHeight < 1 || domNode.clientWidth < 1) { + return; + } if (config.font) { const legendFormatter = label => { @@ -46,7 +52,9 @@ const render = (domNode, config, handlers) => { } function destroy() { - if (plot) plot.shutdown(); + if (plot) { + plot.shutdown(); + } } handlers.onDestroy(destroy); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/size.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/size.js index 1f582170e8f88..adf2e7d3aed8a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/size.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/size.js @@ -53,7 +53,9 @@ const options = { function drawbubbleDefault(ctx, series, x, y, radius, c) { ctx.fillStyle = c; - if (series.bubbles.fill) ctx.globalAlpha = series.bubbles.fill; + if (series.bubbles.fill) { + ctx.globalAlpha = series.bubbles.fill; + } ctx.strokeStyle = c; ctx.lineWidth = Math.round(radius / 3); @@ -61,15 +63,20 @@ function drawbubbleDefault(ctx, series, x, y, radius, c) { ctx.arc(x, y, radius, 0, Math.PI * 2, true); ctx.closePath(); - if (series.bubbles.fill) ctx.fill(); - else ctx.stroke(); + if (series.bubbles.fill) { + ctx.fill(); + } else { + ctx.stroke(); + } } function init(plot) { plot.hooks.processOptions.push(processOptions); function processOptions(plot, options) { - if (options.series.bubbles.active) plot.hooks.drawSeries.push(drawSeries); + if (options.series.bubbles.active) { + plot.hooks.drawSeries.push(drawSeries); + } } function drawSeries(plot, ctx, series) { @@ -88,8 +95,12 @@ function init(plot) { const delta = maxPoint - minPoint; const radius = (function() { - if (size == null) return 0; // If there is no size, draw nothing - if (delta === 0) return series.bubbles.size.min; // If there is no difference between the min and the max, draw the minimum bubble. + if (size == null) { + return 0; + } // If there is no size, draw nothing + if (delta === 0) { + return series.bubbles.size.min; + } // If there is no difference between the min and the max, draw the minimum bubble. // Otherwise draw something between the min and max acceptable radius. return ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js index 7dfcd2c2f2b68..65dc7517453a1 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js @@ -30,7 +30,9 @@ function draw(plot, ctx) { $('.valueLabel', plot.getPlaceholder()).remove(); plot.getData().forEach(function(series) { const show = get(series.numbers, 'show'); - if (!show) return; + if (!show) { + return; + } let points = series.data; @@ -54,7 +56,9 @@ function draw(plot, ctx) { ctx.textAlign = 'center'; function writeText(text, x, y) { - if (typeof text === 'undefined') return; + if (typeof text === 'undefined') { + return; + } const textNode = $('
') .text(String(text)) .addClass('valueLabel') diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js index d7c1885f6388c..99e5fe564196f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js @@ -72,10 +72,12 @@ export const progress = () => ({ text.textContent = label; text.setAttribute('className', 'canvasProgress__label'); - if (shape === 'horizontalPill') + if (shape === 'horizontalPill') { text.setAttribute('x', parseInt(text.getAttribute('x'), 10) + offset / 2); - if (shape === 'verticalPill') + } + if (shape === 'verticalPill') { text.setAttribute('y', parseInt(text.getAttribute('y'), 10) - offset / 2); + } Object.assign(text.style, font.spec); shapeSvg.appendChild(text); @@ -101,7 +103,9 @@ export const progress = () => ({ shapeSvg.setAttribute('width', domNode.offsetWidth); shapeSvg.setAttribute('height', domNode.offsetHeight); - if (domNode.firstChild) domNode.removeChild(domNode.firstChild); + if (domNode.firstChild) { + domNode.removeChild(domNode.firstChild); + } domNode.appendChild(shapeSvg); handlers.onResize(() => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js index 780e5f8acbe8f..120fdeb89c207 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js @@ -24,8 +24,11 @@ export const repeatImage = () => ({ const container = $('
'); function setSize(img) { - if (img.naturalHeight > img.naturalWidth) img.height = settings.size; - else img.width = settings.size; + if (img.naturalHeight > img.naturalWidth) { + img.height = settings.size; + } else { + img.width = settings.size; + } } function finish() { @@ -36,11 +39,15 @@ export const repeatImage = () => ({ const img = new Image(); img.onload = function() { setSize(img); - if (settings.max && settings.count > settings.max) settings.count = settings.max; + if (settings.max && settings.count > settings.max) { + settings.count = settings.max; + } times(settings.count, () => container.append(img.cloneNode(true))); if (isValidUrl(settings.emptyImage)) { - if (settings.max == null) throw new Error('max must be set if using an emptyImage'); + if (settings.max == null) { + throw new Error('max must be set if using an emptyImage'); + } const emptyImage = new Image(); emptyImage.onload = function() { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js index a74fc6f136437..0e2491dcd0b5f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js @@ -42,8 +42,11 @@ export const revealImage = () => ({ function finish() { const firstChild = domNode.firstChild; - if (firstChild) domNode.replaceChild(aligner, firstChild); - else domNode.appendChild(aligner); + if (firstChild) { + domNode.replaceChild(aligner, firstChild); + } else { + domNode.appendChild(aligner); + } handlers.done(); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js index e778a022019f2..f27edb2fe9480 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js @@ -20,8 +20,12 @@ export const shape = () => ({ const shapeContent = shapeSvg.firstElementChild; - if (fill) shapeContent.setAttribute('fill', fill); - if (border) shapeContent.setAttribute('stroke', border); + if (fill) { + shapeContent.setAttribute('fill', fill); + } + if (border) { + shapeContent.setAttribute('stroke', border); + } const strokeWidth = Math.max(borderWidth, 0); shapeContent.setAttribute('stroke-width', strokeWidth); shapeContent.setAttribute('stroke-miterlimit', 999); @@ -64,7 +68,9 @@ export const shape = () => ({ shapeSvg.setAttribute('viewBox', [minX, minY, shapeWidth, shapeHeight].join(' ')); const oldShape = domNode.firstElementChild; - if (oldShape) domNode.removeChild(oldShape); + if (oldShape) { + domNode.removeChild(oldShape); + } domNode.appendChild(shapeSvg); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.js index cdb3ca6290947..66fb062c73a61 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.js @@ -12,7 +12,9 @@ export const DatetimeInput = compose( withState('strValue', 'setStrValue', ({ moment }) => moment.format('YYYY-MM-DD HH:mm:ss')), lifecycle({ componentWillReceiveProps({ moment, setStrValue, setValid }) { - if (this.props.moment.isSame(moment)) return; + if (this.props.moment.isSame(moment)) { + return; + } setStrValue(moment.format('YYYY-MM-DD HH:mm:ss')); setValid(true); }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.js index d9218728b6afa..335db3fcc8f9e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.js @@ -20,9 +20,11 @@ export const DatetimeRangeAbsolute = ({ from, to, onSelect }) => ( onValueChange={val => onSelect(val, to)} onSelect={val => { // sets the time to start of day if only the date was selected - if (moment(from).format('hh:mm:ss a') === val.format('hh:mm:ss a')) + if (moment(from).format('hh:mm:ss a') === val.format('hh:mm:ss a')) { onSelect(val.startOf('day'), to); - else onSelect(val, to); + } else { + onSelect(val, to); + } }} />
@@ -34,9 +36,11 @@ export const DatetimeRangeAbsolute = ({ from, to, onSelect }) => ( onValueChange={val => onSelect(from, val)} onSelect={val => { // set the time to end of day if only the date was selected - if (moment(to).format('hh:mm:ss a') === val.format('hh:mm:ss a')) + if (moment(to).format('hh:mm:ss a') === val.format('hh:mm:ss a')) { onSelect(from, moment(val).endOf('day')); - else onSelect(from, val); + } else { + onSelect(from, val); + } }} />
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.js index 8f85eb9dbaf08..848072e1ee4ec 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.js @@ -43,7 +43,9 @@ export function formatDuration(from, to) { if (to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) { const rounded = fromParts[1].split('/'); text = 'Last ' + rounded[0]; - if (rounded[1]) text = text + ' rounded to the ' + timeUnits[rounded[1]]; + if (rounded[1]) { + text = text + ' rounded to the ' + timeUnits[rounded[1]]; + } return text; } else { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.js index 880afcd35f654..6bcd9db05a86b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.js @@ -26,8 +26,11 @@ export const TimeFilter = ({ compact, filter, setFilter, commit }) => { commit(filter); } - if (compact) return ; - else return ; + if (compact) { + return ; + } else { + return ; + } }; TimeFilter.propTypes = { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/extended_template.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/extended_template.js index c40f17604f9ff..1f7b09c66ae61 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/extended_template.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/extended_template.js @@ -51,7 +51,9 @@ export class ExtendedTemplate extends React.PureComponent { render() { const isDisabled = typeof this.props.argValue === 'boolean' && this.props.argValue === false; - if (isDisabled) return The axis is disabled; + if (isDisabled) { + return The axis is disabled; + } const positions = { xaxis: ['bottom', 'top'], diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js index d60b834931cb3..8f7907dfeeb46 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js @@ -58,14 +58,20 @@ class DatacolumnArgInput extends Component { // if setting size, auto-select the first column if no column is already set if (fn === 'size') { const col = column || (columns[0] && columns[0].name); - if (col) return onValueChange(`${fn}(${maybeQuoteValue(col)})`); + if (col) { + return onValueChange(`${fn}(${maybeQuoteValue(col)})`); + } } // this.inputRefs.column is the column selection, if there is no value, do nothing - if (valueNotSet(column)) return setMathFunction(fn); + if (valueNotSet(column)) { + return setMathFunction(fn); + } // this.inputRefs.fn is the math function to use, if it's not set, just use the value input - if (valueNotSet(fn)) return onValueChange(column); + if (valueNotSet(fn)) { + return onValueChange(column); + } // this.inputRefs.fn has a value, so use it as a math.js expression onValueChange(`${fn}(${maybeQuoteValue(column)})`); @@ -76,7 +82,9 @@ class DatacolumnArgInput extends Component { const options = [{ value: '', text: 'select column', disabled: true }]; sortBy(columns, 'name').forEach(column => { - if (allowedTypes && !allowedTypes.includes(column.type)) return; + if (allowedTypes && !allowedTypes.includes(column.type)) { + return; + } options.push({ value: column.name, text: column.name }); }); @@ -108,7 +116,9 @@ class DatacolumnArgInput extends Component { const EnhancedDatacolumnArgInput = compose( withPropsOnChange(['argValue', 'columns'], ({ argValue, columns }) => ({ mathValue: (argValue => { - if (getType(argValue) !== 'string') return { error: 'argValue is not a string type' }; + if (getType(argValue) !== 'string') { + return { error: 'argValue is not a string type' }; + } try { const matchedCol = columns.find(({ name }) => argValue === name); const val = matchedCol ? maybeQuoteValue(matchedCol.name) : argValue; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/simple_math_function.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/simple_math_function.js index 3da639b3669ad..7f4a333ced00c 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/simple_math_function.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/simple_math_function.js @@ -21,7 +21,9 @@ export const SimpleMathFunction = ({ onChange, value, inputRef, onlymath }) => { { text: 'Unique', value: 'unique' }, ]; - if (!onlymath) options.unshift({ text: 'Value', value: '' }); + if (!onlymath) { + options.unshift({ text: 'Value', value: '' }); + } return ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js index de258b3fe792f..d40182a1121cd 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js @@ -32,7 +32,9 @@ class ImageUpload extends React.Component { let urlType = Object.keys(props.assets).length ? 'asset' : 'file'; // if not a valid base64 string, will show as missing asset icon - if (isValidHttpUrl(url)) urlType = 'link'; + if (isValidHttpUrl(url)) { + urlType = 'link'; + } this.inputRefs = {}; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js index 2090b7d1dc585..d97aa23e041ca 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js @@ -19,10 +19,14 @@ const PaletteArgInput = ({ onValueChange, argValue, renderError }) => { // TODO: This is weird, its basically a reimplementation of what the interpretter would return. // Probably a better way todo this, and maybe a better way to handle template stype objects in general? function astToPalette({ chain }) { - if (chain.length !== 1 || chain[0].function !== 'palette') throwNotParsed(); + if (chain.length !== 1 || chain[0].function !== 'palette') { + throwNotParsed(); + } try { const colors = chain[0].arguments._.map(astObj => { - if (getType(astObj) !== 'string') throwNotParsed(); + if (getType(astObj) !== 'string') { + throwNotParsed(); + } return astObj; }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/toggle.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/toggle.js index 30092cd7bd56c..77eaa5673b330 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/toggle.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/toggle.js @@ -11,7 +11,9 @@ import { templateFromReactComponent } from '../../../public/lib/template_from_re const ToggleArgInput = ({ onValueChange, argValue, argId, renderError }) => { const handleChange = () => onValueChange(!argValue); - if (typeof argValue !== 'boolean') renderError(); + if (typeof argValue !== 'boolean') { + renderError(); + } return ; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js index 37c92226eab35..1596821db0549 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js @@ -13,8 +13,11 @@ import { templateFromReactComponent } from '../../../public/lib/template_from_re class EssqlDatasource extends PureComponent { componentDidMount() { const query = this.getQuery(); - if (typeof query !== 'string') this.setArg(this.getArgName(), this.defaultQuery); - else this.props.setInvalid(!query.trim()); + if (typeof query !== 'string') { + this.setArg(this.getArgName(), this.defaultQuery); + } else { + this.props.setInvalid(!query.trim()); + } } defaultQuery = 'SELECT * FROM "logstash*"'; @@ -25,8 +28,12 @@ class EssqlDatasource extends PureComponent { // and set them for the data source UI. getArgName = () => { const { args } = this.props; - if (getSimpleArg('_', args)[0]) return '_'; - if (getSimpleArg('q', args)[0]) return 'q'; + if (getSimpleArg('_', args)[0]) { + return '_'; + } + if (getSimpleArg('q', args)[0]) { + return 'q'; + } return 'query'; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js index 16f1a70f6763d..4aab56d1eb281 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js @@ -28,8 +28,12 @@ const TimelionDatasource = ({ args, updateArgs }) => { }; const getArgName = () => { - if (getSimpleArg('_', args)[0]) return '_'; - if (getSimpleArg('q', args)[0]) return 'q'; + if (getSimpleArg('_', args)[0]) { + return '_'; + } + if (getSimpleArg('q', args)[0]) { + return 'q'; + } return 'query'; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/math.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/math.js index 22cfe3d486bae..47c43da4a5dab 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/math.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/math.js @@ -22,7 +22,9 @@ export const math = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { columns: [] }; + if (getState(context) !== 'ready') { + return { columns: [] }; + } return { columns: get(getValue(context), 'columns', []) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/point_series.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/point_series.js index ac5ee08d21349..0cc6570b28529 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/point_series.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/point_series.js @@ -43,7 +43,9 @@ export const pointseries = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { columns: [] }; + if (getState(context) !== 'ready') { + return { columns: [] }; + } return { columns: get(getValue(context), 'columns', []) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/transforms/sort.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/transforms/sort.js index a864d4ff55763..e79b81df91428 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/transforms/sort.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/transforms/sort.js @@ -23,7 +23,9 @@ export const sort = () => ({ }, ], resolve({ context }) { - if (getState(context) === 'ready') return { columns: get(getValue(context), 'columns', []) }; + if (getState(context) === 'ready') { + return { columns: get(getValue(context), 'columns', []) }; + } return { columns: [] }; }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/dropdownControl.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/dropdownControl.js index 95370ce177782..573e1259ff001 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/dropdownControl.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/dropdownControl.js @@ -32,7 +32,9 @@ export const dropdownControl = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { columns: [] }; + if (getState(context) !== 'ready') { + return { columns: [] }; + } return { columns: get(getValue(context), 'columns', []) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js index 1975aa8005d4f..f8f290dcdbcf4 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js @@ -81,7 +81,9 @@ export const pie = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { labels: [] }; + if (getState(context) !== 'ready') { + return { labels: [] }; + } return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js index 1f609155a9cf6..bdfa459df90ca 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js @@ -67,7 +67,9 @@ export const plot = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { labels: [] }; + if (getState(context) !== 'ready') { + return { labels: [] }; + } return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/timefilterControl.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/timefilterControl.js index d368e933b88df..6701720dc6ccd 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/timefilterControl.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/timefilterControl.js @@ -23,7 +23,9 @@ export const timefilterControl = () => ({ }, ], resolve({ context }) { - if (getState(context) !== 'ready') return { columns: [] }; + if (getState(context) !== 'ready') { + return { columns: [] }; + } return { columns: get(getValue(context), 'columns', []) }; }, }); diff --git a/x-pack/plugins/canvas/common/functions/to.js b/x-pack/plugins/canvas/common/functions/to.js index afc58b52b692c..6b9ff76a3a643 100644 --- a/x-pack/plugins/canvas/common/functions/to.js +++ b/x-pack/plugins/canvas/common/functions/to.js @@ -20,7 +20,9 @@ export const to = () => ({ }, }, fn: (context, args, { types }) => { - if (!args.type) throw new Error('Must specify a casting type'); + if (!args.type) { + throw new Error('Must specify a casting type'); + } return castProvider(types)(context, args.type); }, diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.js b/x-pack/plugins/canvas/common/lib/autocomplete.js index 8be391aea884a..4b6417aed8e98 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.js +++ b/x-pack/plugins/canvas/common/lib/autocomplete.js @@ -46,11 +46,17 @@ export function getAutocompleteSuggestions(specs, expression, position) { const { ast: newAst, fnIndex, argName, argIndex } = getFnArgAtPosition(ast, position); const fn = newAst.node.chain[fnIndex].node; - if (fn.function.includes(MARKER)) return getFnNameSuggestions(specs, newAst, fnIndex); + if (fn.function.includes(MARKER)) { + return getFnNameSuggestions(specs, newAst, fnIndex); + } - if (argName === '_') return getArgNameSuggestions(specs, newAst, fnIndex, argName, argIndex); + if (argName === '_') { + return getArgNameSuggestions(specs, newAst, fnIndex, argName, argIndex); + } - if (argName) return getArgValueSuggestions(specs, newAst, fnIndex, argName, argIndex); + if (argName) { + return getArgValueSuggestions(specs, newAst, fnIndex, argName, argIndex); + } } catch (e) { // Fail silently } @@ -67,8 +73,9 @@ function getFnArgAtPosition(ast, position) { for (let argIndex = 0; argIndex < argValues.length; argIndex++) { const value = argValues[argIndex]; if (value.start <= position && position <= value.end) { - if (value.node !== null && value.node.type === 'expression') + if (value.node !== null && value.node.type === 'expression') { return getFnArgAtPosition(value, position); + } return { ast, fnIndex, argName, argIndex }; } } @@ -103,7 +110,9 @@ function getArgNameSuggestions(specs, ast, fnIndex, argName, argIndex) { // Get the list of args from the function definition const fn = ast.node.chain[fnIndex].node; const fnDef = getByAlias(specs, fn.function); - if (!fnDef) return []; + if (!fnDef) { + return []; + } // We use the exact text instead of the value because it is always a string and might be quoted const { text, start, end } = fn.arguments[argName][argIndex]; @@ -117,7 +126,9 @@ function getArgNameSuggestions(specs, ast, fnIndex, argName, argIndex) { return [name, values.filter(value => !value.text.includes(MARKER))]; }); const unusedArgDefs = matchingArgDefs.filter(argDef => { - if (argDef.multi) return true; + if (argDef.multi) { + return true; + } return !argEntries.some(([name, values]) => { return values.length && (name === argDef.name || argDef.aliases.includes(name)); }); @@ -141,9 +152,13 @@ function getArgValueSuggestions(specs, ast, fnIndex, argName, argIndex) { // Get the list of values from the argument definition const fn = ast.node.chain[fnIndex].node; const fnDef = getByAlias(specs, fn.function); - if (!fnDef) return []; + if (!fnDef) { + return []; + } const argDef = getByAlias(fnDef.args, argName); - if (!argDef) return []; + if (!argDef) { + return []; + } // Get suggestions from the argument definition, including the default const { start, end, node } = fn.arguments[argName][argIndex]; @@ -169,7 +184,9 @@ function textMatches(text, query) { function maybeQuote(value) { if (typeof value === 'string') { - if (value.match(/^\{.*\}$/)) return value; + if (value.match(/^\{.*\}$/)) { + return value; + } return `"${value.replace(/"/g, '\\"')}"`; } return value; @@ -186,8 +203,12 @@ function unnamedArgComparator(a, b) { } function alphanumericalComparator(a, b) { - if (a < b) return -1; - if (a > b) return 1; + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } return 0; } @@ -198,7 +219,9 @@ function startsWithComparator(query) { function combinedComparator(...comparators) { return (a, b) => comparators.reduce((acc, comparator) => { - if (acc !== 0) return acc; + if (acc !== 0) { + return acc; + } return comparator(a, b); }, 0); } diff --git a/x-pack/plugins/canvas/common/lib/dataurl.js b/x-pack/plugins/canvas/common/lib/dataurl.js index 72eca8cc7f5b1..fc1706e0b1705 100644 --- a/x-pack/plugins/canvas/common/lib/dataurl.js +++ b/x-pack/plugins/canvas/common/lib/dataurl.js @@ -12,17 +12,23 @@ const dataurlRegex = /^data:([a-z]+\/[a-z0-9-+.]+)(;[a-z-]+=[a-z0-9-]+)?(;([a-z0 export const imageTypes = ['image/svg+xml', 'image/jpeg', 'image/png', 'image/gif']; export function parseDataUrl(str, withData = false) { - if (typeof str !== 'string') return; + if (typeof str !== 'string') { + return; + } const matches = str.match(dataurlRegex); - if (!matches) return; + if (!matches) { + return; + } const [, mimetype, charset, , encoding] = matches; // all types except for svg need to be base64 encoded const imageTypeIndex = imageTypes.indexOf(matches[1]); - if (imageTypeIndex > 0 && encoding !== 'base64') return; + if (imageTypeIndex > 0 && encoding !== 'base64') { + return; + } return { mimetype, diff --git a/x-pack/plugins/canvas/common/lib/find_in_object.js b/x-pack/plugins/canvas/common/lib/find_in_object.js index 2664351629ebb..484f718fd81c1 100644 --- a/x-pack/plugins/canvas/common/lib/find_in_object.js +++ b/x-pack/plugins/canvas/common/lib/find_in_object.js @@ -8,8 +8,12 @@ import { each } from 'lodash'; export function findInObject(o, fn, memo, name) { memo = memo || []; - if (fn(o, name)) memo.push(o); - if (o != null && typeof o === 'object') each(o, (val, name) => findInObject(val, fn, memo, name)); + if (fn(o, name)) { + memo.push(o); + } + if (o != null && typeof o === 'object') { + each(o, (val, name) => findInObject(val, fn, memo, name)); + } return memo; } diff --git a/x-pack/plugins/canvas/common/lib/get_field_type.js b/x-pack/plugins/canvas/common/lib/get_field_type.js index 863621b8bccb2..1f326b1042ec1 100644 --- a/x-pack/plugins/canvas/common/lib/get_field_type.js +++ b/x-pack/plugins/canvas/common/lib/get_field_type.js @@ -7,7 +7,9 @@ import { unquoteString } from './unquote_string'; export function getFieldType(columns, field) { - if (!field) return 'null'; + if (!field) { + return 'null'; + } const realField = unquoteString(field); const column = columns.find(column => column.name === realField); return column ? column.type : 'null'; diff --git a/x-pack/plugins/canvas/common/lib/get_legend_config.js b/x-pack/plugins/canvas/common/lib/get_legend_config.js index 85c7733f29c88..10cc2819f192e 100644 --- a/x-pack/plugins/canvas/common/lib/get_legend_config.js +++ b/x-pack/plugins/canvas/common/lib/get_legend_config.js @@ -5,7 +5,9 @@ */ export const getLegendConfig = (legend, size) => { - if (!legend || size < 2) return { show: false }; + if (!legend || size < 2) { + return { show: false }; + } const config = { show: true, diff --git a/x-pack/plugins/canvas/common/lib/handlebars.js b/x-pack/plugins/canvas/common/lib/handlebars.js index ee1b7b40fde59..0b7ef38fe8f6d 100644 --- a/x-pack/plugins/canvas/common/lib/handlebars.js +++ b/x-pack/plugins/canvas/common/lib/handlebars.js @@ -10,7 +10,9 @@ import { pivotObjectArray } from './pivot_object_array'; // example use: {{math rows 'mean(price - cost)' 2}} Hbars.registerHelper('math', (rows, expression, precision) => { - if (!Array.isArray(rows)) return 'MATH ERROR: first argument must be an array'; + if (!Array.isArray(rows)) { + return 'MATH ERROR: first argument must be an array'; + } const value = evaluate(expression, pivotObjectArray(rows)); try { return precision ? value.toFixed(precision) : value; diff --git a/x-pack/plugins/canvas/common/lib/hex_to_rgb.js b/x-pack/plugins/canvas/common/lib/hex_to_rgb.js index 1bb0acfd45cab..bb2c6d2d3518f 100644 --- a/x-pack/plugins/canvas/common/lib/hex_to_rgb.js +++ b/x-pack/plugins/canvas/common/lib/hex_to_rgb.js @@ -9,10 +9,14 @@ export const hexToRgb = hex => { const hexColor = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; const shorthandMatches = shorthandHexColor.exec(hex); - if (shorthandMatches) return shorthandMatches.slice(1, 4).map(hex => parseInt(hex + hex, 16)); + if (shorthandMatches) { + return shorthandMatches.slice(1, 4).map(hex => parseInt(hex + hex, 16)); + } const hexMatches = hexColor.exec(hex); - if (hexMatches) return hexMatches.slice(1, 4).map(hex => parseInt(hex, 16)); + if (hexMatches) { + return hexMatches.slice(1, 4).map(hex => parseInt(hex, 16)); + } return null; }; diff --git a/x-pack/plugins/canvas/common/lib/pivot_object_array.js b/x-pack/plugins/canvas/common/lib/pivot_object_array.js index 974e327a46e7b..ca191ece3ce05 100644 --- a/x-pack/plugins/canvas/common/lib/pivot_object_array.js +++ b/x-pack/plugins/canvas/common/lib/pivot_object_array.js @@ -10,7 +10,9 @@ const isString = val => typeof val === 'string'; export function pivotObjectArray(rows, columns) { const columnNames = columns || Object.keys(rows[0]); - if (!columnNames.every(isString)) throw new Error('Columns should be an array of strings'); + if (!columnNames.every(isString)) { + throw new Error('Columns should be an array of strings'); + } const columnValues = map(columnNames, name => map(rows, name)); return zipObject(columnNames, columnValues); diff --git a/x-pack/plugins/canvas/common/lib/resolve_dataurl.js b/x-pack/plugins/canvas/common/lib/resolve_dataurl.js index ef33a09e004f8..3063b5200c26b 100644 --- a/x-pack/plugins/canvas/common/lib/resolve_dataurl.js +++ b/x-pack/plugins/canvas/common/lib/resolve_dataurl.js @@ -19,7 +19,11 @@ export const resolveFromArgs = (args, defaultDataurl = null) => { }; export const resolveWithMissingImage = (img, alt = null) => { - if (isValidUrl(img)) return img; - if (img === null) return alt; + if (isValidUrl(img)) { + return img; + } + if (img === null) { + return alt; + } return missingImage; }; diff --git a/x-pack/plugins/canvas/common/lib/unquote_string.js b/x-pack/plugins/canvas/common/lib/unquote_string.js index 0760960c53cb2..0d6a31004d0b1 100644 --- a/x-pack/plugins/canvas/common/lib/unquote_string.js +++ b/x-pack/plugins/canvas/common/lib/unquote_string.js @@ -5,7 +5,11 @@ */ export const unquoteString = str => { - if (/^"/.test(str)) return str.replace(/^"(.+(?="$))"$/, '$1'); - if (/^'/.test(str)) return str.replace(/^'(.+(?='$))'$/, '$1'); + if (/^"/.test(str)) { + return str.replace(/^"(.+(?="$))"$/, '$1'); + } + if (/^'/.test(str)) { + return str.replace(/^'(.+(?='$))'$/, '$1'); + } return str; }; diff --git a/x-pack/plugins/canvas/init.js b/x-pack/plugins/canvas/init.js index b838dfe3fa95d..d91c7e8a70e52 100644 --- a/x-pack/plugins/canvas/init.js +++ b/x-pack/plugins/canvas/init.js @@ -17,7 +17,9 @@ export default async function(server /*options*/) { const basePath = config.get('server.basePath'); const reportingBrowserType = (() => { const configKey = 'xpack.reporting.capture.browser.type'; - if (!config.has(configKey)) return null; + if (!config.has(configKey)) { + return null; + } return config.get(configKey); })(); const kibanaVars = await server.getInjectedUiAppVars('kibana'); diff --git a/x-pack/plugins/canvas/public/apps/export/routes.js b/x-pack/plugins/canvas/public/apps/export/routes.js index 7ec6a59c7ecbe..a0eafe3e3ffe9 100644 --- a/x-pack/plugins/canvas/public/apps/export/routes.js +++ b/x-pack/plugins/canvas/public/apps/export/routes.js @@ -24,7 +24,9 @@ export const routes = [ const pageNumber = parseInt(params.page, 10); // redirect to home app on invalid workpad id or page number - if (fetchedWorkpad == null && isNaN(pageNumber)) return router.redirectTo('home'); + if (fetchedWorkpad == null && isNaN(pageNumber)) { + return router.redirectTo('home'); + } const { assets, ...workpad } = fetchedWorkpad; dispatch(setAssets(assets)); diff --git a/x-pack/plugins/canvas/public/apps/workpad/routes.js b/x-pack/plugins/canvas/public/apps/workpad/routes.js index 1efe744f36889..c638bb2afa174 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/routes.js +++ b/x-pack/plugins/canvas/public/apps/workpad/routes.js @@ -32,7 +32,9 @@ export const routes = [ notify.error(err, { title: `Couldn't create workpad` }); // TODO: remove this and switch to checking user privileges when canvas loads when granular app privileges are introduced // https://github.com/elastic/kibana/issues/20277 - if (err.response.status === 403) dispatch(setCanUserWrite(false)); + if (err.response.status === 403) { + dispatch(setCanUserWrite(false)); + } router.redirectTo('home'); } }, @@ -58,7 +60,9 @@ export const routes = [ // TODO: remove this and switch to checking user privileges when canvas loads when granular app privileges are introduced // https://github.com/elastic/kibana/issues/20277 workpadService.update(params.id, fetchedWorkpad).catch(err => { - if (err.response.status === 403) dispatch(setCanUserWrite(false)); + if (err.response.status === 403) { + dispatch(setCanUserWrite(false)); + } }); } catch (err) { notify.error(err, { title: `Couldn't load workpad with ID` }); @@ -71,12 +75,15 @@ export const routes = [ const pageNumber = parseInt(params.page, 10); // no page provided, append current page to url - if (isNaN(pageNumber)) + if (isNaN(pageNumber)) { return router.redirectTo('loadWorkpad', { id: workpad.id, page: workpad.page + 1 }); + } // set the active page using the number provided in the url const pageIndex = pageNumber - 1; - if (pageIndex !== workpad.page) dispatch(gotoPage(pageIndex)); + if (pageIndex !== workpad.page) { + dispatch(gotoPage(pageIndex)); + } }, meta: { component: WorkpadApp, diff --git a/x-pack/plugins/canvas/public/components/app/app.js b/x-pack/plugins/canvas/public/components/app/app.js index 0f933ace4b6e2..a961291e6dd31 100644 --- a/x-pack/plugins/canvas/public/components/app/app.js +++ b/x-pack/plugins/canvas/public/components/app/app.js @@ -49,7 +49,9 @@ export class App extends React.PureComponent { }; render() { - if (this.props.appState instanceof Error) return this.renderError(); + if (this.props.appState instanceof Error) { + return this.renderError(); + } return (
diff --git a/x-pack/plugins/canvas/public/components/arg_form/advanced_failure.js b/x-pack/plugins/canvas/public/components/arg_form/advanced_failure.js index f06fff92f6eca..a973bfd65b9ed 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/advanced_failure.js +++ b/x-pack/plugins/canvas/public/components/arg_form/advanced_failure.js @@ -27,7 +27,9 @@ export const AdvancedFailureComponent = props => { resetErrorState(); // when setting a new value, attempt to reset the error state - if (valid) return onValueChange(fromExpression(argExpression.trim(), 'argument')); + if (valid) { + return onValueChange(fromExpression(argExpression.trim(), 'argument')); + } }; const confirmReset = ev => { diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js index e872dd3743cdc..cff38431deb15 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js @@ -21,7 +21,9 @@ const branches = [ const { argType } = argTypeInstance; // arg does not need to be resolved, no need to branch - if (!argType.resolveArgValue) return false; + if (!argType.resolveArgValue) { + return false; + } // arg needs to be resolved, render pending if the value is not defined return typeof resolvedArgValue === 'undefined'; diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js index eb11c401b89e6..4cc2df4838931 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js @@ -32,10 +32,14 @@ class ArgTemplateFormComponent extends React.Component { componentWillUpdate(prevProps) { //see if error state changed - if (this.props.error !== prevProps.error) this.props.handlers.destroy(); + if (this.props.error !== prevProps.error) { + this.props.handlers.destroy(); + } } componentDidUpdate() { - if (this.props.error) return this.renderErrorTemplate(); + if (this.props.error) { + return this.renderErrorTemplate(); + } this.renderTemplate(this.domNode); } @@ -45,7 +49,9 @@ class ArgTemplateFormComponent extends React.Component { renderTemplate = domNode => { const { template, argumentProps, handlers } = this.props; - if (template) return template(domNode, argumentProps, handlers); + if (template) { + return template(domNode, argumentProps, handlers); + } }; renderErrorTemplate = () => { @@ -56,9 +62,13 @@ class ArgTemplateFormComponent extends React.Component { render() { const { template, error } = this.props; - if (error) return this.renderErrorTemplate(); + if (error) { + return this.renderErrorTemplate(); + } - if (!template) return null; + if (!template) { + return null; + } return ( 0) this.setState({ selectedIndex: selectedIndex - 1 }); - else this.setState({ selectedIndex: items.length - 1 }); + if (selectedIndex > 0) { + this.setState({ selectedIndex: selectedIndex - 1 }); + } else { + this.setState({ selectedIndex: items.length - 1 }); + } } selectNext() { const { items } = this.props; const { selectedIndex } = this.state; - if (selectedIndex >= 0 && selectedIndex < items.length - 1) + if (selectedIndex >= 0 && selectedIndex < items.length - 1) { this.setState({ selectedIndex: selectedIndex + 1 }); - else this.setState({ selectedIndex: 0 }); + } else { + this.setState({ selectedIndex: 0 }); + } } scrollIntoView() { @@ -105,7 +113,9 @@ export class Autocomplete extends React.Component { state: { selectedIndex }, } = this; const itemRef = itemRefs[selectedIndex]; - if (!containerRef || !itemRef) return; + if (!containerRef || !itemRef) { + return; + } containerRef.scrollTop = Math.max( Math.min(containerRef.scrollTop, itemRef.offsetTop), itemRef.offsetTop + itemRef.offsetHeight - containerRef.offsetHeight @@ -129,7 +139,9 @@ export class Autocomplete extends React.Component { const { items } = this.props; const { isOpen, selectedIndex } = this.state; - if ([ESCAPE, LEFT, RIGHT].includes(keyCode)) this.setState({ isOpen: false }); + if ([ESCAPE, LEFT, RIGHT].includes(keyCode)) { + this.setState({ isOpen: false }); + } if ([TAB, ENTER].includes(keyCode) && isOpen && selectedIndex >= 0) { e.preventDefault(); diff --git a/x-pack/plugins/canvas/public/components/clipboard/clipboard.js b/x-pack/plugins/canvas/public/components/clipboard/clipboard.js index 4be4471eb0d23..72ed24dc5f100 100644 --- a/x-pack/plugins/canvas/public/components/clipboard/clipboard.js +++ b/x-pack/plugins/canvas/public/components/clipboard/clipboard.js @@ -21,7 +21,9 @@ export class Clipboard extends React.PureComponent { const result = copy(content, { debug: true }); - if (typeof onCopy === 'function') onCopy(result); + if (typeof onCopy === 'function') { + onCopy(result); + } }; render() { diff --git a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.js b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.js index bf842540e4b51..ee0a281f4672a 100644 --- a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.js +++ b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.js @@ -31,7 +31,9 @@ export const ConfirmModal = props => { }; // render nothing if this component isn't open - if (!isOpen) return null; + if (!isOpen) { + return null; + } return ( diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js index e0240a3a8ef36..ee713f8234e73 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js @@ -43,9 +43,13 @@ export class DatasourceComponent extends PureComponent { componentDidUpdate(prevProps) { const { args, resetArgs, datasource, selectDatasource } = this.props; - if (!isEqual(prevProps.args, args)) resetArgs(); + if (!isEqual(prevProps.args, args)) { + resetArgs(); + } - if (!isEqual(prevProps.datasource, datasource)) selectDatasource(datasource); + if (!isEqual(prevProps.datasource, datasource)) { + selectDatasource(datasource); + } } getDatasourceFunctionNode = (name, args) => ({ @@ -96,8 +100,9 @@ export class DatasourceComponent extends PureComponent { setInvalid, } = this.props; - if (selecting) + if (selecting) { return ; + } const datasourcePreview = previewing ? ( { const datasourceAst = get(element, 'ast.chain', []) .map((astDef, i) => { // if it's not a function, it's can't be a datasource - if (astDef.type !== 'function') return; + if (astDef.type !== 'function') { + return; + } const args = astDef.arguments; // if there's no matching datasource in the registry, we're done const datasource = datasourceRegistry.get(astDef.function); - if (!datasource) return; + if (!datasource) { + return; + } const datasourceDef = getDataTableFunctionsByName(datasource.name); diff --git a/x-pack/plugins/canvas/public/components/datatable/datatable.js b/x-pack/plugins/canvas/public/components/datatable/datatable.js index 4381ae9f699b1..e0cd3378ff65c 100644 --- a/x-pack/plugins/canvas/public/components/datatable/datatable.js +++ b/x-pack/plugins/canvas/public/components/datatable/datatable.js @@ -11,7 +11,9 @@ import moment from 'moment'; import { Paginate } from '../paginate'; const getIcon = type => { - if (type === null) return; + if (type === null) { + return; + } let icon; switch (type) { @@ -39,7 +41,9 @@ const getColumnName = col => (typeof col === 'string' ? col : col.name); const getColumnType = col => col.type || null; const getFormattedValue = (val, type) => { - if (type === 'date') return moment(val).format(); + if (type === 'date') { + return moment(val).format(); + } return String(val); }; diff --git a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js index 6cadc77109e46..77d1a8d3c2bc1 100644 --- a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js +++ b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js @@ -38,7 +38,9 @@ export class DomPreview extends React.Component { } update = original => () => { - if (!this.content || !this.container) return; + if (!this.content || !this.container) { + return; + } const thumb = original.cloneNode(true); @@ -50,7 +52,9 @@ export class DomPreview extends React.Component { const scale = thumbHeight / originalHeight; const thumbWidth = originalWidth * scale; - if (this.content.hasChildNodes()) this.content.removeChild(this.content.firstChild); + if (this.content.hasChildNodes()) { + this.content.removeChild(this.content.firstChild); + } this.content.appendChild(thumb); this.content.style.cssText = `transform: scale(${scale}); transform-origin: top left;`; diff --git a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js index e2afd9e2e0459..7f61a6a37ed31 100644 --- a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js +++ b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js @@ -37,7 +37,9 @@ export class ElementShareContainer extends React.PureComponent { // dispatches a custom DOM event on the container when the element is complete onComplete(() => { clearTimeout(this.timeout); - if (!this.sharedItemRef) return; // without this, crazy fast forward/backward paging leads to an error + if (!this.sharedItemRef) { + return; + } // without this, crazy fast forward/backward paging leads to an error const ev = new CustomEvent('renderComplete'); this.sharedItemRef.dispatchEvent(ev); diff --git a/x-pack/plugins/canvas/public/components/element_types/element_types.js b/x-pack/plugins/canvas/public/components/element_types/element_types.js index 074ffcaa8cee7..ced13040a2d5d 100644 --- a/x-pack/plugins/canvas/public/components/element_types/element_types.js +++ b/x-pack/plugins/canvas/public/components/element_types/element_types.js @@ -39,10 +39,18 @@ export const ElementTypes = ({ elements, onClick, search, setSearch }) => { ); - if (!search) return card; - if (includes(lowerCase(name), search)) return card; - if (includes(lowerCase(displayName), search)) return card; - if (includes(lowerCase(help), search)) return card; + if (!search) { + return card; + } + if (includes(lowerCase(name), search)) { + return card; + } + if (includes(lowerCase(displayName), search)) { + return card; + } + if (includes(lowerCase(help), search)) { + return card; + } return null; }); diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js index 6f6452a954980..6ae35603de623 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js @@ -32,7 +32,9 @@ export class ElementWrapper extends React.PureComponent { render() { // wait until the handlers have been created - if (!this.state.handlers) return null; + if (!this.state.handlers) { + return null; + } const { renderable, transformMatrix, width, height, state } = this.props; diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js index 52b4041ccb074..d918467e9d437 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js @@ -24,7 +24,9 @@ export function createHandlers(element, pageId, dispatch) { }, done() { - if (isComplete) return; // don't emit if the element is already done + if (isComplete) { + return; + } // don't emit if the element is already done isComplete = true; completeFn(); }, diff --git a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js index ba679c4a3940c..425a7885a94d5 100644 --- a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js +++ b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js @@ -25,8 +25,11 @@ export function createStatefulPropHoc(fieldname, updater = 'updateValue') { } handleChange = ev => { - if (ev.target) this.setState({ value: ev.target.value }); - else this.setState({ value: ev }); + if (ev.target) { + this.setState({ value: ev.target.value }); + } else { + this.setState({ value: ev }); + } }; render() { diff --git a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js index b5c1c233da33a..636d9b0006ac6 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js @@ -20,7 +20,9 @@ export const ESFieldSelect = ({ value, fields = [], onChange, onFocus, onBlur }) onChange={([field]) => onChange(get(field, 'label', null))} onSearchChange={searchValue => { // resets input when user starts typing - if (searchValue) onChange(null); + if (searchValue) { + onChange(null); + } }} onFocus={onFocus} onBlur={onBlur} diff --git a/x-pack/plugins/canvas/public/components/es_field_select/index.js b/x-pack/plugins/canvas/public/components/es_field_select/index.js index fc39b626d62cd..2dc2484083241 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/index.js @@ -12,7 +12,9 @@ export const ESFieldSelect = compose( withState('fields', 'setFields', []), lifecycle({ componentDidMount() { - if (this.props.index) getFields(this.props.index).then(this.props.setFields); + if (this.props.index) { + getFields(this.props.index).then(this.props.setFields); + } }, componentDidUpdate({ index }) { const { value, onChange, setFields } = this.props; @@ -22,7 +24,9 @@ export const ESFieldSelect = compose( }); } - if (value && !this.props.fields.includes(value)) onChange(null); + if (value && !this.props.fields.includes(value)) { + onChange(null); + } }, }) )(Component); diff --git a/x-pack/plugins/canvas/public/components/es_fields_select/index.js b/x-pack/plugins/canvas/public/components/es_fields_select/index.js index 8a73666dc7865..aa607a9ebea4a 100644 --- a/x-pack/plugins/canvas/public/components/es_fields_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_fields_select/index.js @@ -12,8 +12,9 @@ export const ESFieldsSelect = compose( withState('fields', 'setFields', []), lifecycle({ componentDidMount() { - if (this.props.index) + if (this.props.index) { getFields(this.props.index).then((fields = []) => this.props.setFields(fields)); + } }, componentDidUpdate({ index }) { const { setFields, onChange, selected } = this.props; diff --git a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js index 035cae6fbba06..eff835e84e411 100644 --- a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js +++ b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js @@ -21,7 +21,9 @@ export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBl onChange={([index]) => onChange(get(index, 'label', defaultIndex).toLowerCase())} onSearchChange={searchValue => { // resets input when user starts typing - if (searchValue) onChange(defaultIndex); + if (searchValue) { + onChange(defaultIndex); + } }} onBlur={onBlur} onFocus={onFocus} diff --git a/x-pack/plugins/canvas/public/components/es_index_select/index.js b/x-pack/plugins/canvas/public/components/es_index_select/index.js index ae85b562d006c..ea656b6fffd4a 100644 --- a/x-pack/plugins/canvas/public/components/es_index_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_index_select/index.js @@ -17,7 +17,9 @@ export const ESIndexSelect = compose( const { setLoading, setIndices, value, onChange } = this.props; setLoading(false); setIndices(indices.sort()); - if (!value && indices.length) onChange(indices[0]); + if (!value && indices.length) { + onChange(indices[0]); + } }); }, }) diff --git a/x-pack/plugins/canvas/public/components/expression/index.js b/x-pack/plugins/canvas/public/components/expression/index.js index 5360b76a9e937..61dd91141af3e 100644 --- a/x-pack/plugins/canvas/public/components/expression/index.js +++ b/x-pack/plugins/canvas/public/components/expression/index.js @@ -46,7 +46,9 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { const { element, pageId } = stateProps; const allProps = { ...ownProps, ...stateProps, ...dispatchProps }; - if (!element) return allProps; + if (!element) { + return allProps; + } const { expression } = element; diff --git a/x-pack/plugins/canvas/public/components/expression_input/argument_reference.js b/x-pack/plugins/canvas/public/components/expression_input/argument_reference.js index dd72f0080024b..82dd1d84b5962 100644 --- a/x-pack/plugins/canvas/public/components/expression_input/argument_reference.js +++ b/x-pack/plugins/canvas/public/components/expression_input/argument_reference.js @@ -32,9 +32,15 @@ function getHelp(argDef) { function getArgListItems(argDef) { const { aliases, types, default: def, required } = argDef; const items = []; - if (aliases.length) items.push({ title: 'Aliases', description: aliases.join(', ') }); - if (types.length) items.push({ title: 'Types', description: types.join(', ') }); - if (def != null) items.push({ title: 'Default', description: def }); + if (aliases.length) { + items.push({ title: 'Aliases', description: aliases.join(', ') }); + } + if (types.length) { + items.push({ title: 'Types', description: types.join(', ') }); + } + if (def != null) { + items.push({ title: 'Default', description: def }); + } items.push({ title: 'Required', description: String(Boolean(required)) }); return items; } diff --git a/x-pack/plugins/canvas/public/components/expression_input/expression_input.js b/x-pack/plugins/canvas/public/components/expression_input/expression_input.js index 7ea1aa8f6f698..d1888495a256c 100644 --- a/x-pack/plugins/canvas/public/components/expression_input/expression_input.js +++ b/x-pack/plugins/canvas/public/components/expression_input/expression_input.js @@ -33,21 +33,27 @@ export class ExpressionInput extends React.Component { } componentDidUpdate() { - if (!this.ref) return; + if (!this.ref) { + return; + } const { selection } = this.state; const { start, end } = selection; this.ref.setSelectionRange(start, end); } undo() { - if (!this.undoHistory.length) return; + if (!this.undoHistory.length) { + return; + } const value = this.undoHistory.pop(); this.redoHistory.push(this.props.value); this.props.onChange(value); } redo() { - if (!this.redoHistory.length) return; + if (!this.redoHistory.length) { + return; + } const value = this.redoHistory.pop(); this.undoHistory.push(this.props.value); this.props.onChange(value); @@ -66,8 +72,11 @@ export class ExpressionInput extends React.Component { if (e.ctrlKey || e.metaKey) { if (e.key === 'z') { e.preventDefault(); - if (e.shiftKey) this.redo(); - else this.undo(); + if (e.shiftKey) { + this.redo(); + } else { + this.undo(); + } } if (e.key === 'y') { e.preventDefault(); @@ -109,7 +118,9 @@ export class ExpressionInput extends React.Component { getHeader = () => { const { suggestions } = this.state; - if (!suggestions.length) return ''; + if (!suggestions.length) { + return ''; + } return (

{startCase(suggestions[0].type)}

@@ -119,8 +130,12 @@ export class ExpressionInput extends React.Component { getReference = selectedItem => { const { fnDef, argDef } = selectedItem || {}; - if (argDef) return ; - if (fnDef) return ; + if (argDef) { + return ; + } + if (fnDef) { + return ; + } const { fnDef: fnDefAtPosition, argDef: argDefAtPosition } = getFnArgDefAtPosition( this.props.functionDefinitions, @@ -128,8 +143,12 @@ export class ExpressionInput extends React.Component { this.state.selection.start ); - if (argDefAtPosition) return ; - if (fnDefAtPosition) return ; + if (argDefAtPosition) { + return ; + } + if (fnDefAtPosition) { + return ; + } return ''; }; diff --git a/x-pack/plugins/canvas/public/components/expression_input/function_reference.js b/x-pack/plugins/canvas/public/components/expression_input/function_reference.js index 0f9076b7613a8..03a1d57cf8590 100644 --- a/x-pack/plugins/canvas/public/components/expression_input/function_reference.js +++ b/x-pack/plugins/canvas/public/components/expression_input/function_reference.js @@ -45,9 +45,15 @@ function getHelp(fnDef) { function getFnListItems(fnDef) { const { aliases, context, type } = fnDef; const items = []; - if (aliases.length) items.push({ title: 'Aliases', description: aliases.join(', ') }); - if (context.types) items.push({ title: 'Accepts', description: context.types.join(', ') }); - if (type) items.push({ title: 'Returns', description: type }); + if (aliases.length) { + items.push({ title: 'Aliases', description: aliases.join(', ') }); + } + if (context.types) { + items.push({ title: 'Accepts', description: context.types.join(', ') }); + } + if (type) { + items.push({ title: 'Returns', description: type }); + } return items; } @@ -64,7 +70,9 @@ function getArgItems(args) { function getArgColumns() { return ['argument', 'aliases', 'types', 'default', 'description'].map(field => { const column = { field, name: startCase(field), truncateText: field !== 'description' }; - if (field === 'description') column.width = '50%'; + if (field === 'description') { + column.width = '50%'; + } return column; }); } diff --git a/x-pack/plugins/canvas/public/components/fullscreen_control/fullscreen_control.js b/x-pack/plugins/canvas/public/components/fullscreen_control/fullscreen_control.js index 3b56129c27417..7985e468d8f57 100644 --- a/x-pack/plugins/canvas/public/components/fullscreen_control/fullscreen_control.js +++ b/x-pack/plugins/canvas/public/components/fullscreen_control/fullscreen_control.js @@ -18,8 +18,9 @@ export class FullscreenControl extends React.PureComponent { const { children, isFullscreen } = this.props; const keyHandler = action => { - if (action === 'FULLSCREEN' || (isFullscreen && action === 'FULLSCREEN_EXIT')) + if (action === 'FULLSCREEN' || (isFullscreen && action === 'FULLSCREEN_EXIT')) { this.toggleFullscreen(); + } }; return ( diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.js b/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.js index f70d39e511924..3b43365b5dc8b 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.js +++ b/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.js @@ -30,7 +30,9 @@ export class FunctionFormContextPending extends React.PureComponent { fetchContext = (props, force = false) => { // dispatch context update if none is provided const { expressionType, context, updateContext } = props; - if (force || (context == null && expressionType.requiresContext)) updateContext(); + if (force || (context == null && expressionType.requiresContext)) { + updateContext(); + } }; render() { diff --git a/x-pack/plugins/canvas/public/components/function_form/index.js b/x-pack/plugins/canvas/public/components/function_form/index.js index 0f7b348eea78a..fbde896361cb6 100644 --- a/x-pack/plugins/canvas/public/components/function_form/index.js +++ b/x-pack/plugins/canvas/public/components/function_form/index.js @@ -96,7 +96,9 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { const existingId = Object.keys(assets).find( assetId => assets[assetId].type === type && assets[assetId].value === content ); - if (existingId) return existingId; + if (existingId) { + return existingId; + } return onAssetAdd(type, content); }, }; diff --git a/x-pack/plugins/canvas/public/components/function_form_list/index.js b/x-pack/plugins/canvas/public/components/function_form_list/index.js index 7f60a43835eba..00046c65c947f 100644 --- a/x-pack/plugins/canvas/public/components/function_form_list/index.js +++ b/x-pack/plugins/canvas/public/components/function_form_list/index.js @@ -12,7 +12,9 @@ import { modelRegistry, viewRegistry, transformRegistry } from '../../expression import { FunctionFormList as Component } from './function_form_list'; function normalizeContext(chain) { - if (!Array.isArray(chain) || !chain.length) return null; + if (!Array.isArray(chain) || !chain.length) { + return null; + } return { type: 'expression', chain, diff --git a/x-pack/plugins/canvas/public/components/item_grid/item_grid.js b/x-pack/plugins/canvas/public/components/item_grid/item_grid.js index 063ee849013d9..156d348f38dcd 100644 --- a/x-pack/plugins/canvas/public/components/item_grid/item_grid.js +++ b/x-pack/plugins/canvas/public/components/item_grid/item_grid.js @@ -11,11 +11,15 @@ import { last } from 'lodash'; const defaultPerRow = 6; export const ItemGrid = ({ items, itemsPerRow, children }) => { - if (!items) return null; + if (!items) { + return null; + } const rows = items.reduce( (rows, item) => { - if (last(rows).length >= (itemsPerRow || defaultPerRow)) rows.push([]); + if (last(rows).length >= (itemsPerRow || defaultPerRow)) { + rows.push([]); + } last(rows).push(children({ item })); diff --git a/x-pack/plugins/canvas/public/components/link/link.js b/x-pack/plugins/canvas/public/components/link/link.js index 5e7810e0db7ab..3f8e65c31f97a 100644 --- a/x-pack/plugins/canvas/public/components/link/link.js +++ b/x-pack/plugins/canvas/public/components/link/link.js @@ -24,7 +24,9 @@ export class Link extends React.PureComponent { }; navigateTo = (name, params) => ev => { - if (this.props.onClick) this.props.onClick(ev); + if (this.props.onClick) { + this.props.onClick(ev); + } if ( !ev.defaultPrevented && // onClick prevented default diff --git a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js index 922c323545def..0b49998a3d58b 100644 --- a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js +++ b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js @@ -46,7 +46,9 @@ export class PageManager extends React.PureComponent { componentDidUpdate(prevProps) { // scrolls to the active page on the next tick, otherwise new pages don't scroll completely into view - if (prevProps.selectedPage !== this.props.selectedPage) setTimeout(this.scrollToActivePage, 0); + if (prevProps.selectedPage !== this.props.selectedPage) { + setTimeout(this.scrollToActivePage, 0); + } } componentWillUnmount() { @@ -57,7 +59,9 @@ export class PageManager extends React.PureComponent { if (this.activePageRef && this.pageListRef) { // not all target browsers support element.scrollTo // TODO: replace this with something more cross-browser, maybe scrollIntoView - if (!this.pageListRef.scrollTo) return; + if (!this.pageListRef.scrollTo) { + return; + } const pageOffset = this.activePageRef.offsetLeft; const { @@ -95,13 +99,17 @@ export class PageManager extends React.PureComponent { doDelete = () => { const { previousPage, removePage, deleteId, selectedPage } = this.props; this.resetDelete(); - if (deleteId === selectedPage) previousPage(); + if (deleteId === selectedPage) { + previousPage(); + } removePage(deleteId); }; onDragEnd = ({ draggableId: pageId, source, destination }) => { // dropped outside the list - if (!destination) return; + if (!destination) { + return; + } const position = destination.index - source.index; @@ -128,7 +136,9 @@ export class PageManager extends React.PureComponent { page.id === selectedPage ? 'canvasPageManager__page-isActive' : '' }`} ref={el => { - if (page.id === selectedPage) this.activePageRef = el; + if (page.id === selectedPage) { + this.activePageRef = el; + } provided.innerRef(el); }} {...provided.draggableProps} diff --git a/x-pack/plugins/canvas/public/components/paginate/index.js b/x-pack/plugins/canvas/public/components/paginate/index.js index 2854324c3981a..ce1e525d50c9f 100644 --- a/x-pack/plugins/canvas/public/components/paginate/index.js +++ b/x-pack/plugins/canvas/public/components/paginate/index.js @@ -14,7 +14,9 @@ export const Paginate = compose( totalPages: Math.ceil(rows.length / (perPage || 10)), })), withState('currentPage', 'setPage', ({ startPage, totalPages }) => { - if (totalPages > 0) return Math.min(startPage, totalPages - 1); + if (totalPages > 0) { + return Math.min(startPage, totalPages - 1); + } return 0; }), withProps(({ rows, totalPages, currentPage, perPage }) => { @@ -36,7 +38,9 @@ export const Paginate = compose( }), lifecycle({ componentDidUpdate(prevProps) { - if (prevProps.perPage !== this.props.perPage) this.props.setPage(0); + if (prevProps.perPage !== this.props.perPage) { + this.props.setPage(0); + } }, }) )(Component); diff --git a/x-pack/plugins/canvas/public/components/popover/popover.js b/x-pack/plugins/canvas/public/components/popover/popover.js index 89de57aa845d9..0c72abe91c96c 100644 --- a/x-pack/plugins/canvas/public/components/popover/popover.js +++ b/x-pack/plugins/canvas/public/components/popover/popover.js @@ -31,7 +31,9 @@ export class Popover extends Component { }; componentDidMount() { - if (this.props.isOpen) this.setState({ isPopoverOpen: true }); + if (this.props.isOpen) { + this.setState({ isPopoverOpen: true }); + } } handleClick = () => { diff --git a/x-pack/plugins/canvas/public/components/refresh_control/refresh_control.js b/x-pack/plugins/canvas/public/components/refresh_control/refresh_control.js index cdc41e123d89d..d3a22542a5767 100644 --- a/x-pack/plugins/canvas/public/components/refresh_control/refresh_control.js +++ b/x-pack/plugins/canvas/public/components/refresh_control/refresh_control.js @@ -12,13 +12,17 @@ import { AutoRefreshControls } from './auto_refresh_controls'; const getRefreshInterval = (val = '') => { // if it's a number, just use it directly - if (!isNaN(Number(val))) return val; + if (!isNaN(Number(val))) { + return val; + } // if it's a string, try to parse out the shorthand duration value const match = String(val).match(/^([0-9]{1,})([hmsd])$/); // TODO: do something better with improper input, like show an error... - if (!match) return; + if (!match) { + return; + } switch (match[2]) { case 's': diff --git a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js index b47424fb5c25e..cb9912e717173 100644 --- a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js +++ b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js @@ -21,7 +21,9 @@ export class RenderToDom extends React.Component { componentDidUpdate() { // Calls render function once we have the reference to the DOM element to render into - if (this.props.domNode) this.props.render(this.props.domNode); + if (this.props.domNode) { + this.props.render(this.props.domNode); + } } render() { diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js index f859c15d1b1ac..3896e604362f5 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js +++ b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js @@ -44,7 +44,9 @@ export class RenderWithFn extends React.Component { componentWillReceiveProps({ renderFn }) { const newRenderFunction = renderFn !== this.props.renderFn; - if (newRenderFunction) this.resetRenderTarget(this.domNode); + if (newRenderFunction) { + this.resetRenderTarget(this.domNode); + } } shouldComponentUpdate(prevProps) { @@ -60,7 +62,9 @@ export class RenderWithFn extends React.Component { } // Size changes - if (!isEqual(size, prevProps.size)) return handlers.resize(size); + if (!isEqual(size, prevProps.size)) { + return handlers.resize(size); + } } componentWillUnmount() { @@ -70,7 +74,9 @@ export class RenderWithFn extends React.Component { callRenderFn = () => { const { handlers, config, renderFn, reuseNode, name: functionName } = this.props; // TODO: We should wait until handlers.done() is called before replacing the element content? - if (!reuseNode || !this.renderTarget) this.resetRenderTarget(this.domNode); + if (!reuseNode || !this.renderTarget) { + this.resetRenderTarget(this.domNode); + } // else if (!firstRender) handlers.destroy(); const renderConfig = cloneDeep(config); @@ -88,12 +94,18 @@ export class RenderWithFn extends React.Component { resetRenderTarget = domNode => { const { handlers } = this.props; - if (!domNode) throw new Error('RenderWithFn can not reset undefined target node'); + if (!domNode) { + throw new Error('RenderWithFn can not reset undefined target node'); + } // call destroy on existing element - if (!this.firstRender) handlers.destroy(); + if (!this.firstRender) { + handlers.destroy(); + } - while (domNode.firstChild) domNode.removeChild(domNode.firstChild); + while (domNode.firstChild) { + domNode.removeChild(domNode.firstChild); + } this.firstRender = true; this.renderTarget = this.createRenderTarget(); diff --git a/x-pack/plugins/canvas/public/components/router/router.js b/x-pack/plugins/canvas/public/components/router/router.js index 800c01079fcec..44df1f2b7b842 100644 --- a/x-pack/plugins/canvas/public/components/router/router.js +++ b/x-pack/plugins/canvas/public/components/router/router.js @@ -47,8 +47,9 @@ export class Router extends React.PureComponent { if (!component) { // TODO: render some kind of 404 page, maybe from a prop? - if (process.env.NODE_ENV !== 'production') + if (process.env.NODE_ENV !== 'production') { console.warn(`No component defined on route: ${route.name}`); + } return; } @@ -73,8 +74,9 @@ export class Router extends React.PureComponent { render() { // show loading - if (this.props.showLoading) + if (this.props.showLoading) { return React.createElement(CanvasLoading, { msg: this.props.loadingMessage }); + } // show the activeComponent return isClassComponent(this.state.activeComponent) diff --git a/x-pack/plugins/canvas/public/components/toolbar/toolbar.js b/x-pack/plugins/canvas/public/components/toolbar/toolbar.js index b05f027f1c334..ad41219ca367f 100644 --- a/x-pack/plugins/canvas/public/components/toolbar/toolbar.js +++ b/x-pack/plugins/canvas/public/components/toolbar/toolbar.js @@ -41,7 +41,9 @@ export const Toolbar = props => { const done = () => setTray(null); const showHideTray = exp => { - if (tray && tray === exp) return done(); + if (tray && tray === exp) { + return done(); + } setTray(exp); }; diff --git a/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.js b/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.js index 9afdf5e06138d..207e7156393fe 100644 --- a/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.js +++ b/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.js @@ -16,7 +16,9 @@ export const TooltipIcon = ({ icon = 'info', ...rest }) => { info: { type: 'iInCircle', color: 'default' }, }; - if (!Object.keys(icons).includes(icon)) throw new Error(`Unsupported icon type: ${icon}`); + if (!Object.keys(icons).includes(icon)) { + throw new Error(`Unsupported icon type: ${icon}`); + } return ; }; diff --git a/x-pack/plugins/canvas/public/components/workpad/index.js b/x-pack/plugins/canvas/public/components/workpad/index.js index f99af9679c4b0..40ae5e1d1a664 100644 --- a/x-pack/plugins/canvas/public/components/workpad/index.js +++ b/x-pack/plugins/canvas/public/components/workpad/index.js @@ -46,8 +46,12 @@ export const Workpad = compose( withState('prevSelectedPageNumber', 'setPrevSelectedPageNumber', 0), withProps(({ selectedPageNumber, prevSelectedPageNumber, transition }) => { function getAnimation(pageNumber) { - if (!transition || !transition.name) return null; - if (![selectedPageNumber, prevSelectedPageNumber].includes(pageNumber)) return null; + if (!transition || !transition.name) { + return null; + } + if (![selectedPageNumber, prevSelectedPageNumber].includes(pageNumber)) { + return null; + } const { enter, exit } = transitionsRegistry.get(transition.name); const laterPageNumber = Math.max(selectedPageNumber, prevSelectedPageNumber); const name = pageNumber === laterPageNumber ? enter : exit; @@ -59,11 +63,15 @@ export const Workpad = compose( }), withHandlers({ onPageChange: props => pageNumber => { - if (pageNumber === props.selectedPageNumber) return; + if (pageNumber === props.selectedPageNumber) { + return; + } props.setPrevSelectedPageNumber(props.selectedPageNumber); const transitionPage = Math.max(props.selectedPageNumber, pageNumber) - 1; const { transition } = props.workpad.pages[transitionPage]; - if (transition) props.setTransition(transition); + if (transition) { + props.setTransition(transition); + } props.router.navigateTo('loadWorkpad', { id: props.workpad.id, page: pageNumber }); }, }), diff --git a/x-pack/plugins/canvas/public/components/workpad/workpad.js b/x-pack/plugins/canvas/public/components/workpad/workpad.js index b424212257638..dcdbed0ecea65 100644 --- a/x-pack/plugins/canvas/public/components/workpad/workpad.js +++ b/x-pack/plugins/canvas/public/components/workpad/workpad.js @@ -39,16 +39,28 @@ export const Workpad = props => { const keyHandler = action => { // handle keypress events for editor and presentation events // this exists in both contexts - if (action === 'REFRESH') return fetchAllRenderables(); + if (action === 'REFRESH') { + return fetchAllRenderables(); + } // editor events - if (action === 'UNDO') return undoHistory(); - if (action === 'REDO') return redoHistory(); - if (action === 'GRID') return setGrid(!grid); + if (action === 'UNDO') { + return undoHistory(); + } + if (action === 'REDO') { + return redoHistory(); + } + if (action === 'GRID') { + return setGrid(!grid); + } // presentation events - if (action === 'PREV') return previousPage(); - if (action === 'NEXT') return nextPage(); + if (action === 'PREV') { + return previousPage(); + } + if (action === 'NEXT') { + return nextPage(); + } }; setDocTitle(workpad.name); diff --git a/x-pack/plugins/canvas/public/components/workpad_export/index.js b/x-pack/plugins/canvas/public/components/workpad_export/index.js index eaa4691b71839..a54acaca01404 100644 --- a/x-pack/plugins/canvas/public/components/workpad_export/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_export/index.js @@ -24,7 +24,9 @@ const mapStateToProps = state => ({ const getAbsoluteUrl = path => { const { location } = getWindow(); - if (!location) return path; // fallback for mocked window object + if (!location) { + return path; + } // fallback for mocked window object const { protocol, hostname, port } = location; return `${protocol}//${hostname}:${port}${path}`; @@ -34,13 +36,16 @@ export const WorkpadExport = compose( connect(mapStateToProps), withProps(({ workpad, pageCount }) => ({ getExportUrl: type => { - if (type === 'pdf') return getAbsoluteUrl(getPdfUrl(workpad, { pageCount })); + if (type === 'pdf') { + return getAbsoluteUrl(getPdfUrl(workpad, { pageCount })); + } throw new Error(`Unknown export type: ${type}`); }, onCopy: type => { - if (type === 'pdf') + if (type === 'pdf') { return notify.info('The PDF generation URL was copied to your clipboard.'); + } throw new Error(`Unknown export type: ${type}`); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_export/utils.js b/x-pack/plugins/canvas/public/components/workpad_export/utils.js index be2e7e6d8114c..9fefaef09b9ab 100644 --- a/x-pack/plugins/canvas/public/components/workpad_export/utils.js +++ b/x-pack/plugins/canvas/public/components/workpad_export/utils.js @@ -28,8 +28,9 @@ export function getPdfUrl({ id, name: title, width, height }, { pageCount }) { // build a list of all page urls for exporting, they are captured one at a time const workpadUrls = []; - for (let i = 1; i <= pageCount; i++) + for (let i = 1; i <= pageCount; i++) { workpadUrls.push(rison.encode(`${canvasEntry}/export/workpad/pdf/${id}/page/${i}`)); + } const jobParams = { browserTimezone: 'America/Phoenix', // TODO: get browser timezone, or Kibana setting? diff --git a/x-pack/plugins/canvas/public/components/workpad_header/workpad_header.js b/x-pack/plugins/canvas/public/components/workpad_header/workpad_header.js index 0e8e209d31411..c4fa1ce706229 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/workpad_header.js +++ b/x-pack/plugins/canvas/public/components/workpad_header/workpad_header.js @@ -33,7 +33,9 @@ export const WorkpadHeader = ({ showElementModal, }) => { const keyHandler = action => { - if (action === 'EDITING') toggleWriteable(); + if (action === 'EDITING') { + toggleWriteable(); + } }; const elementAdd = ( @@ -61,8 +63,11 @@ export const WorkpadHeader = ({ let readOnlyToolTip = ''; - if (!canUserWrite) readOnlyToolTip = "You don't have permission to edit this workpad"; - else readOnlyToolTip = isWriteable ? 'Hide editing controls' : 'Show editing controls'; + if (!canUserWrite) { + readOnlyToolTip = "You don't have permission to edit this workpad"; + } else { + readOnlyToolTip = isWriteable ? 'Hide editing controls' : 'Show editing controls'; + } return (
diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/index.js b/x-pack/plugins/canvas/public/components/workpad_loader/index.js index 6229fd340813a..8e83819054fdb 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/index.js @@ -46,7 +46,9 @@ export const WorkpadLoader = compose( notify.error(err, { title: `Couldn't upload workpad` }); // TODO: remove this and switch to checking user privileges when canvas loads when granular app privileges are introduced // https://github.com/elastic/kibana/issues/20277 - if (err.response.status === 403) props.setCanUserWrite(false); + if (err.response.status === 403) { + props.setCanUserWrite(false); + } } return; } @@ -87,7 +89,9 @@ export const WorkpadLoader = compose( notify.error(err, { title: `Couldn't clone workpad` }); // TODO: remove this and switch to checking user privileges when canvas loads when granular app privileges are introduced // https://github.com/elastic/kibana/issues/20277 - if (err.response.status === 403) props.setCanUserWrite(false); + if (err.response.status === 403) { + props.setCanUserWrite(false); + } } }, @@ -110,13 +114,17 @@ export const WorkpadLoader = compose( const [passes, errors] = results.reduce( ([passes, errors], result) => { - if (result.id === loadedWorkpad && !result.err) redirectHome = true; + if (result.id === loadedWorkpad && !result.err) { + redirectHome = true; + } if (result.err) { errors.push(result.id); // TODO: remove this and switch to checking user privileges when canvas loads when granular app privileges are introduced // https://github.com/elastic/kibana/issues/20277 - if (result.err.response.status === 403) props.setCanUserWrite(false); + if (result.err.response.status === 403) { + props.setCanUserWrite(false); + } } else { passes.push(result.id); } @@ -133,11 +141,15 @@ export const WorkpadLoader = compose( workpads: remainingWorkpads, }; - if (errors.length > 0) notify.error("Couldn't delete all workpads"); + if (errors.length > 0) { + notify.error("Couldn't delete all workpads"); + } setWorkpads(workpadState); - if (redirectHome) props.router.navigateTo('home'); + if (redirectHome) { + props.router.navigateTo('home'); + } return errors.map(({ id }) => id); }); diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/upload_workpad.js b/x-pack/plugins/canvas/public/components/workpad_loader/upload_workpad.js index c09ea63280cef..f304377535f02 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/upload_workpad.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/upload_workpad.js @@ -9,7 +9,9 @@ import { getId } from '../../lib/get_id'; import { notify } from '../../lib/notify'; export const uploadWorkpad = (file, onUpload) => { - if (!file) return; + if (!file) { + return; + } if (get(file, 'type') !== 'application/json') { return notify.warning('Only JSON files are accepted', { diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js index 70a951c892eb3..66def18abaf8f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js @@ -62,7 +62,9 @@ export class WorkpadLoader extends React.PureComponent { componentWillReceiveProps(newProps) { // the workpadId prop will change when a is created or loaded, close the toolbar when it does const { workpadId, onClose } = this.props; - if (workpadId !== newProps.workpadId) onClose(); + if (workpadId !== newProps.workpadId) { + onClose(); + } } componentWillUnmount() { diff --git a/x-pack/plugins/canvas/public/components/workpad_page/event_handlers.js b/x-pack/plugins/canvas/public/components/workpad_page/event_handlers.js index 4771221f8b169..e37c703de4ba6 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/event_handlers.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/event_handlers.js @@ -7,10 +7,15 @@ import { withHandlers } from 'recompose'; const ancestorElement = element => { - if (!element) return element; + if (!element) { + return element; + } // IE11 has no classList on SVG elements, but we're not interested in SVG elements - do if (element.classList && element.classList.contains('canvasPage')) return element; - while ((element = element.parentElement || element.parentNode)); // no IE11 SVG parentElement + do { + if (element.classList && element.classList.contains('canvasPage')) { + return element; + } + } while ((element = element.parentElement || element.parentNode)); // no IE11 SVG parentElement }; const localMousePosition = (box, clientX, clientY) => { @@ -29,7 +34,9 @@ const setupHandler = (commit, target) => { // Ancestor has to be identified on setup, rather than 1st interaction, otherwise events may be triggered on // DOM elements that had been removed: kibana-canvas github issue #1093 const canvasPage = ancestorElement(target); - if (!canvasPage) return; + if (!canvasPage) { + return; + } const canvasOrigin = canvasPage.getBoundingClientRect(); window.onmousemove = ({ clientX, clientY, altKey, metaKey, shiftKey, ctrlKey }) => { const { x, y } = localMousePosition(canvasOrigin, clientX, clientY); @@ -78,7 +85,9 @@ const handleMouseDown = (commit, e, isEditable) => { return; // left-click and edit mode only } const ancestor = ancestorElement(target); - if (!ancestor) return; + if (!ancestor) { + return; + } const { x, y } = localMousePosition(ancestor, clientX, clientY); setupHandler(commit, ancestor); commit('mouseEvent', { event: 'mouseDown', x, y, altKey, metaKey, shiftKey, ctrlKey }); diff --git a/x-pack/plugins/canvas/public/components/workpad_page/index.js b/x-pack/plugins/canvas/public/components/workpad_page/index.js index 58bc2bc06ebd4..be63a36409e6e 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/index.js @@ -32,7 +32,9 @@ const mapDispatchToProps = dispatch => { }; const getRootElementId = (lookup, id) => { - if (!lookup.has(id)) return null; + if (!lookup.has(id)) { + return null; + } const element = lookup.get(id); return element.parent && element.parent.subtype !== 'adHocGroup' @@ -47,12 +49,16 @@ export const WorkpadPage = compose( ), withProps(({ isSelected, animation }) => { function getClassName() { - if (animation) return animation.name; + if (animation) { + return animation.name; + } return isSelected ? 'canvasPage--isActive' : 'canvasPage--isInactive'; } function getAnimationStyle() { - if (!animation) return {}; + if (!animation) { + return {}; + } return { animationDirection: animation.direction, // TODO: Make this configurable @@ -85,8 +91,9 @@ export const WorkpadPage = compose( let element = null; if (elementLookup.has(shape.id)) { element = elementLookup.get(shape.id); - if (selectedElementIds.indexOf(shape.id) > -1) + if (selectedElementIds.indexOf(shape.id) > -1) { selectedElements.push({ ...element, id: shape.id }); + } } // instead of just combining `element` with `shape`, we make property transfer explicit return element ? { ...shape, filter: element.filter } : shape; @@ -101,7 +108,9 @@ export const WorkpadPage = compose( }, remove: () => { // currently, handle the removal of one element, exploiting multiselect subsequently - if (selectedElementIds.length) removeElements(page.id)(selectedElementIds); + if (selectedElementIds.length) { + removeElements(page.id)(selectedElementIds); + } }, copyElements: () => { if (selectedElements.length) { @@ -118,7 +127,9 @@ export const WorkpadPage = compose( }, pasteElements: () => { const elements = JSON.parse(getClipboardData()); - if (elements) elements.map(element => duplicateElement(page.id)(element)); + if (elements) { + elements.map(element => duplicateElement(page.id)(element)); + } }, }; } diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_page.js index 3ee13a4070b7a..30cccb1d398c5 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_page.js @@ -125,7 +125,9 @@ export class WorkpadPage extends PureComponent { {elements .map(element => { if (element.type === 'annotation') { - if (!isEditable) return; + if (!isEditable) { + return; + } const props = { key: element.id, type: element.type, diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js index 8752d7be19612..ae50b5a843da5 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js +++ b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js @@ -52,9 +52,13 @@ export class WorkpadTemplates extends React.PureComponent { clauses.forEach(clause => { const { type, field, value } = clause; // extract terms from the query AST - if (type === 'term') searchTerms.push(value); + if (type === 'term') { + searchTerms.push(value); + } // extracts tags from the query AST - else if (field === 'tags') filterTags.push(value); + else if (field === 'tags') { + filterTags.push(value); + } }); this.setState({ searchTerm: searchTerms.join(' '), filterTags }); @@ -101,7 +105,9 @@ export class WorkpadTemplates extends React.PureComponent { dataType: 'string', width: '30%', render: tags => { - if (!tags) return 'No tags'; + if (!tags) { + return 'No tags'; + } return tags.map(tag => ( {tag} diff --git a/x-pack/plugins/canvas/public/expression_types/arg.js b/x-pack/plugins/canvas/public/expression_types/arg.js index 341bd1e3953fa..6213fc2d44131 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg.js +++ b/x-pack/plugins/canvas/public/expression_types/arg.js @@ -12,8 +12,12 @@ import { argTypeRegistry } from './arg_type'; export class Arg { constructor(props) { const argType = argTypeRegistry.get(props.argType); - if (!argType) throw new Error(`Invalid arg type: ${props.argType}`); - if (!props.name) throw new Error('Args must have a name property'); + if (!argType) { + throw new Error(`Invalid arg type: ${props.argType}`); + } + if (!props.name) { + throw new Error('Args must have a name property'); + } // properties that can be overridden const defaultProps = { diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.js b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.js index 0ef8cef2a50bc..5a8b3ce96a114 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.js @@ -23,7 +23,9 @@ export const AppearanceForm = ({ padding, opacity, overflow, onChange }) => { const paddingVal = padding ? padding.replace('px', '') : ''; const namedChange = name => ev => { - if (name === 'padding') return onChange(name, `${ev.target.value}px`); + if (name === 'padding') { + return onChange(name, `${ev.target.value}px`); + } onChange(name, ev.target.value); }; diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.js b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.js index 7884640831ffe..841158a8fe5d1 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.js @@ -34,12 +34,18 @@ export const BorderForm = ({ value, radius, onChange, colors }) => { const radiusVal = radius ? radius.replace('px', '') : ''; const namedChange = name => val => { - if (name === 'borderWidth') return onChange('border', `${val}px ${borderStyle} ${borderColor}`); + if (name === 'borderWidth') { + return onChange('border', `${val}px ${borderStyle} ${borderColor}`); + } if (name === 'borderStyle') { - if (val === '') return onChange('border', `0px`); + if (val === '') { + return onChange('border', `0px`); + } return onChange('border', `${borderWidth} ${val} ${borderColor}`); } - if (name === 'borderRadius') return onChange('borderRadius', `${val}px`); + if (name === 'borderRadius') { + return onChange('borderRadius', `${val}px`); + } onChange(name, val); }; diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/index.js b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/index.js index 8661413c0b1e4..da751fb5bc59b 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/index.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/index.js @@ -13,17 +13,22 @@ import { ExtendedTemplate } from './extended_template'; const EnhancedExtendedTemplate = lifecycle({ formatLabel(label) { - if (typeof label !== 'string') this.props.renderError(); + if (typeof label !== 'string') { + this.props.renderError(); + } return `Style: ${label}`; }, componentWillMount() { const label = get(this.props.argValue, 'chain.0.arguments.label.0', ''); - if (label) this.props.setLabel(this.formatLabel(label)); + if (label) { + this.props.setLabel(this.formatLabel(label)); + } }, componentWillReceiveProps(newProps) { const newLabel = get(newProps.argValue, 'chain.0.arguments.label.0', ''); - if (newLabel && this.props.label !== this.formatLabel(newLabel)) + if (newLabel && this.props.label !== this.formatLabel(newLabel)) { this.props.setLabel(this.formatLabel(newLabel)); + } }, })(ExtendedTemplate); diff --git a/x-pack/plugins/canvas/public/expression_types/base_form.js b/x-pack/plugins/canvas/public/expression_types/base_form.js index 4b97f6204a355..a9082529585dd 100644 --- a/x-pack/plugins/canvas/public/expression_types/base_form.js +++ b/x-pack/plugins/canvas/public/expression_types/base_form.js @@ -6,7 +6,9 @@ export class BaseForm { constructor(props) { - if (!props.name) throw new Error('Expression specs require a name property'); + if (!props.name) { + throw new Error('Expression specs require a name property'); + } this.name = props.name; this.displayName = props.displayName || this.name; diff --git a/x-pack/plugins/canvas/public/expression_types/datasources/esdocs.js b/x-pack/plugins/canvas/public/expression_types/datasources/esdocs.js index a2436f0e92681..2a3a25f49fa3c 100644 --- a/x-pack/plugins/canvas/public/expression_types/datasources/esdocs.js +++ b/x-pack/plugins/canvas/public/expression_types/datasources/esdocs.js @@ -25,8 +25,12 @@ const EsdocsDatasource = ({ args, updateArgs }) => { // TODO: This is a terrible way of doing defaults. We need to find a way to read the defaults for the function // and set them for the data source UI. const getArgName = () => { - if (getSimpleArg('_', args)[0]) return '_'; - if (getSimpleArg('q', args)[0]) return 'q'; + if (getSimpleArg('_', args)[0]) { + return '_'; + } + if (getSimpleArg('q', args)[0]) { + return 'q'; + } return 'query'; }; @@ -40,7 +44,9 @@ const EsdocsDatasource = ({ args, updateArgs }) => { const getFields = () => { const commas = getSimpleArg('fields', args)[0] || ''; - if (commas.length === 0) return []; + if (commas.length === 0) { + return []; + } return commas.split(',').map(str => str.trim()); }; diff --git a/x-pack/plugins/canvas/public/expression_types/function_form.js b/x-pack/plugins/canvas/public/expression_types/function_form.js index ba58424b7b8c3..299b57e4854c1 100644 --- a/x-pack/plugins/canvas/public/expression_types/function_form.js +++ b/x-pack/plugins/canvas/public/expression_types/function_form.js @@ -28,7 +28,9 @@ export class FunctionForm extends BaseForm { const { argType, expressionIndex } = passedProps; // TODO: show some information to the user than an argument was skipped - if (!arg || skipRender) return null; + if (!arg || skipRender) { + return null; + } const renderArgWithProps = (argValue, valueIndex) => arg.render({ @@ -43,7 +45,9 @@ export class FunctionForm extends BaseForm { // render the argument's template, wrapped in a remove control // if the argument is required but not included, render the control anyway - if (!argValues && arg.required) return renderArgWithProps({ type: undefined, value: '' }, 0); + if (!argValues && arg.required) { + return renderArgWithProps({ type: undefined, value: '' }, 0); + } // render all included argument controls return argValues && argValues.map(renderArgWithProps); @@ -55,8 +59,12 @@ export class FunctionForm extends BaseForm { const { arg, argValues, skipRender } = dataArg; // skip arguments that aren't defined in the expression type schema - if (!arg || arg.required || skipRender) return null; - if (argValues && !arg.multi) return null; + if (!arg || arg.required || skipRender) { + return null; + } + if (argValues && !arg.multi) { + return null; + } const value = arg.default == null ? null : fromExpression(arg.default, 'argument'); @@ -74,7 +82,9 @@ export class FunctionForm extends BaseForm { // Don't instaniate these until render time, to give the registries a chance to populate. const argInstances = this.args.map(argSpec => new Arg(argSpec)); - if (!isPlainObject(args)) throw new Error(`Form "${this.name}" expects "args" object`); + if (!isPlainObject(args)) { + throw new Error(`Form "${this.name}" expects "args" object`); + } // get a mapping of arg values from the expression and from the renderable's schema const argNames = uniq(argInstances.map(arg => arg.name).concat(Object.keys(args))); @@ -99,7 +109,9 @@ export class FunctionForm extends BaseForm { const argumentForms = compact(resolvedDataArgs.map(d => this.renderArg(props, d))); const addableArgs = compact(resolvedDataArgs.map(d => this.getAddableArg(props, d))); - if (!addableArgs.length && !argumentForms.length) return null; + if (!addableArgs.length && !argumentForms.length) { + return null; + } return ( diff --git a/x-pack/plugins/canvas/public/expression_types/model.js b/x-pack/plugins/canvas/public/expression_types/model.js index 1bdcbdeefb50a..812ccab9cc104 100644 --- a/x-pack/plugins/canvas/public/expression_types/model.js +++ b/x-pack/plugins/canvas/public/expression_types/model.js @@ -12,8 +12,12 @@ const NO_NEXT_EXP = 'no next expression'; const MISSING_MODEL_ARGS = 'missing model args'; function getModelArgs(expressionType) { - if (!expressionType) return NO_NEXT_EXP; - if (!expressionType.modelArgs) return MISSING_MODEL_ARGS; + if (!expressionType) { + return NO_NEXT_EXP; + } + if (!expressionType.modelArgs) { + return MISSING_MODEL_ARGS; + } return expressionType.modelArgs.length > 0 ? expressionType.modelArgs : MISSING_MODEL_ARGS; } @@ -45,12 +49,16 @@ export class Model extends FunctionForm { } // if there is no following expression, argument is skipped - if (modelArgs === NO_NEXT_EXP) return { skipRender: true }; + if (modelArgs === NO_NEXT_EXP) { + return { skipRender: true }; + } // if argument is missing from modelArgs, mark it as skipped const argName = get(dataArg, 'arg.name'); const modelArg = modelArgs.find(modelArg => { - if (Array.isArray(modelArg)) return modelArg[0] === argName; + if (Array.isArray(modelArg)) { + return modelArg[0] === argName; + } return modelArg === argName; }); diff --git a/x-pack/plugins/canvas/public/expression_types/view.js b/x-pack/plugins/canvas/public/expression_types/view.js index 6d0b6cd7a2817..166a242d2bae8 100644 --- a/x-pack/plugins/canvas/public/expression_types/view.js +++ b/x-pack/plugins/canvas/public/expression_types/view.js @@ -22,8 +22,9 @@ export class View extends FunctionForm { this.modelArgs = this.modelArgs || []; - if (!Array.isArray(this.modelArgs)) + if (!Array.isArray(this.modelArgs)) { throw new Error(`${this.name} element is invalid, modelArgs must be an array`); + } } } diff --git a/x-pack/plugins/canvas/public/functions/asset.js b/x-pack/plugins/canvas/public/functions/asset.js index 52c9d45e9fd09..115bdc2ab257d 100644 --- a/x-pack/plugins/canvas/public/functions/asset.js +++ b/x-pack/plugins/canvas/public/functions/asset.js @@ -26,7 +26,9 @@ export const asset = () => ({ fn: (context, args) => { const assetId = args.id; const asset = getAssetById(getState(), assetId); - if (asset !== undefined) return asset.value; + if (asset !== undefined) { + return asset.value; + } throw new Error('Could not get the asset by ID: ' + assetId); }, diff --git a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js index c9f89763435d1..68c45d0eb7e4b 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js @@ -112,7 +112,9 @@ describe.skip('historyProvider', () => { describe('onChange', () => { const createOnceHandler = (history, done, fn) => { const teardown = history.onChange((location, prevLocation) => { - if (typeof fn === 'function') fn(location, prevLocation); + if (typeof fn === 'function') { + fn(location, prevLocation); + } teardown(); done(); }); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js index d7ad63032c8a8..2df87fecdb562 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js @@ -68,9 +68,17 @@ const disjunctiveUnion = (keyFun, set1, set2) => const mean = (a, b) => (a + b) / 2; const shallowEqual = (a, b) => { - if (a === b) return true; - if (a.length !== b.length) return false; - for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + if (a === b) { + return true; + } + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } return true; }; diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js index 284cf34212d2f..d527ad3c16587 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js @@ -57,10 +57,15 @@ const cursorPosition = selectReduce((previous, position) => position || previous const mouseButton = selectReduce( (prev, next) => { - if (!next) return prev; + if (!next) { + return prev; + } const { event, uid } = next; - if (event === 'mouseDown') return { down: true, uid }; - else return event === 'mouseUp' ? { down: false, uid } : prev; + if (event === 'mouseDown') { + return { down: true, uid }; + } else { + return event === 'mouseUp' ? { down: false, uid } : prev; + } }, { down: false, uid: null } )(mouseButtonEvent); @@ -97,8 +102,11 @@ const mouseButtonStateTransitions = (state, mouseIsDown, movedAlready) => { case 'up': return mouseIsDown ? 'downed' : 'up'; case 'downed': - if (mouseIsDown) return movedAlready ? 'dragging' : 'downed'; - else return 'up'; + if (mouseIsDown) { + return movedAlready ? 'dragging' : 'downed'; + } else { + return 'up'; + } case 'dragging': return mouseIsDown ? 'dragging' : 'up'; diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/layout.js b/x-pack/plugins/canvas/public/lib/aeroelastic/layout.js index 93bd4ed8c8648..8994eab961d34 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/layout.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/layout.js @@ -273,9 +273,13 @@ const selectionState = select( down: prev.down, }; } - if (selectedShapeObjects) prev.shapes = selectedShapeObjects.slice(); + if (selectedShapeObjects) { + prev.shapes = selectedShapeObjects.slice(); + } // take action on mouse down only, and if the uid changed (except with directSelect), ie. bail otherwise - if (mouseButtonUp || (uidUnchanged && !directSelect)) return { ...prev, down, uid, metaHeld }; + if (mouseButtonUp || (uidUnchanged && !directSelect)) { + return { ...prev, down, uid, metaHeld }; + } const selectFunction = config.singleSelect || !multiselect ? singleSelect : multiSelect; return selectFunction(prev, hoveredShapes, metaHeld, uid, selectedShapeObjects); } @@ -307,7 +311,9 @@ const rotationManipulation = ({ alterSnapGesture, }) => { // rotate around a Z-parallel line going through the shape center (ie. around the center) - if (!shape || !directShape) return { transforms: [], shapes: [] }; + if (!shape || !directShape) { + return { transforms: [], shapes: [] }; + } const center = shape.transformMatrix; const centerPosition = matrix.mvMultiply(center, matrix.ORIGIN); const vector = matrix.mvMultiply( @@ -371,7 +377,9 @@ const minimumSize = ({ a, b, baseAB }, vector) => { const centeredResizeManipulation = ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) - if (!shape || !directShape) return { transforms: [], shapes: [] }; + if (!shape || !directShape) { + return { transforms: [], shapes: [] }; + } // transform the incoming `transform` so that resizing is aligned with shape orientation const vector = matrix.mvMultiply( matrix.multiply( @@ -397,7 +405,9 @@ const centeredResizeManipulation = ({ gesture, shape, directShape }) => { const asymmetricResizeManipulation = ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) - if (!shape || !directShape) return { transforms: [], shapes: [] }; + if (!shape || !directShape) { + return { transforms: [], shapes: [] }; + } // transform the incoming `transform` so that resizing is aligned with shape orientation const compositeComponent = matrix.compositeComponent(shape.localTransformMatrix); const inv = matrix.invert(compositeComponent); // rid the translate component @@ -640,7 +650,9 @@ const shapeCascadeProperties = shapes => shape => { const cascadeProperties = shapes => shapes.map(shapeCascadeProperties(shapes)); const nextShapes = select((preexistingShapes, restated) => { - if (restated && restated.newShapes) return restated.newShapes; + if (restated && restated.newShapes) { + return restated.newShapes; + } // this is the per-shape model update at the current PoC level return preexistingShapes; @@ -657,12 +669,18 @@ const alignmentGuides = (shapes, guidedShapes, draggedShape) => { // todo switch to informative variable names for (let i = 0; i < guidedShapes.length; i++) { const d = guidedShapes[i]; - if (d.type === 'annotation') continue; // fixme avoid this by not letting annotations get in here + if (d.type === 'annotation') { + continue; + } // fixme avoid this by not letting annotations get in here // key points of the dragged shape bounding box for (let j = 0; j < shapes.length; j++) { const referenceShape = shapes[j]; - if (referenceShape.type === 'annotation') continue; // fixme avoid this by not letting annotations get in here - if (referenceShape.parent) continue; // for now, don't snap to grouped elements fixme could snap, but make sure transform is gloabl + if (referenceShape.type === 'annotation') { + continue; + } // fixme avoid this by not letting annotations get in here + if (referenceShape.parent) { + continue; + } // for now, don't snap to grouped elements fixme could snap, but make sure transform is gloabl const s = d.id === referenceShape.id ? { @@ -675,7 +693,9 @@ const alignmentGuides = (shapes, guidedShapes, draggedShape) => { // key points of the stationery shape for (let k = -1; k < 2; k++) { for (let l = -1; l < 2; l++) { - if ((k && !l) || (!k && l)) continue; // don't worry about midpoints of the edges, only the center + if ((k && !l) || (!k && l)) { + continue; + } // don't worry about midpoints of the edges, only the center if ( draggedShape.subtype === config.resizeHandleName && !( @@ -685,12 +705,15 @@ const alignmentGuides = (shapes, guidedShapes, draggedShape) => { // moved midpoint on vertical border (extremeVertical === 0 && l !== 0 && extremeHorizontal === k) ) - ) + ) { continue; + } const D = landmarkPoint(d, k, l); for (let m = -1; m < 2; m++) { for (let n = -1; n < 2; n++) { - if ((m && !n) || (!m && n)) continue; // don't worry about midpoints of the edges, only the center + if ((m && !n) || (!m && n)) { + continue; + } // don't worry about midpoints of the edges, only the center const S = landmarkPoint(s, m, n); for (let dim = 0; dim < 2; dim++) { const orthogonalDimension = 1 - dim; @@ -797,7 +820,9 @@ const hoverAnnotations = select((hoveredShape, selectedPrimaryShapeIds, draggedS const rotationAnnotation = (shapes, selectedShapes, shape, i) => { const foundShape = shapes.find(s => shape.id === s.id); - if (!foundShape) return false; + if (!foundShape) { + return false; + } if (foundShape.type === 'annotation') { return rotationAnnotation( @@ -894,7 +919,9 @@ function resizeAnnotation(shapes, selectedShapes, shape) { (foundShape.subtype === config.resizeHandleName ? shapes.find(s => shape.parent === s.id) : foundShape); - if (!foundShape) return []; + if (!foundShape) { + return []; + } if (foundShape.subtype === config.resizeHandleName) { // preserve any interactive annotation when handling @@ -906,8 +933,9 @@ function resizeAnnotation(shapes, selectedShapes, shape) { : []; return result; } - if (foundShape.type === 'annotation') + if (foundShape.type === 'annotation') { return resizeAnnotation(shapes, selectedShapes, shapes.find(s => foundShape.parent === s.id)); + } // fixme left active: snap wobble. right active: opposite side wobble. const a = snappedA(properShape); @@ -980,7 +1008,9 @@ const translateShapeSnap = (horizontalConstraint, verticalConstraint, draggedEle const snapOffsetX = constrainedX ? -horizontalConstraint.signedDistance : 0; const snapOffsetY = constrainedY ? -verticalConstraint.signedDistance : 0; if (constrainedX || constrainedY) { - if (!snapOffsetX && !snapOffsetY) return shape; + if (!snapOffsetX && !snapOffsetY) { + return shape; + } const snapOffset = matrix.translateComponent( matrix.multiply( matrix.rotateZ((matrix.matrixToAngle(draggedElement.localTransformMatrix) / 180) * Math.PI), @@ -1057,8 +1087,9 @@ const snappedShapes = select( const subtype = draggedShape && draggedShape.subtype; // snapping doesn't come into play if there's no dragging, or it's not a resize drag or translate drag on a // leaf element or a group element: - if (subtype && [config.resizeHandleName, config.adHocGroupName].indexOf(subtype) === -1) + if (subtype && [config.resizeHandleName, config.adHocGroupName].indexOf(subtype) === -1) { return contentShapes; + } const constraints = alignmentGuideAnnotations; // fixme split concept of snap constraints and their annotations const relaxed = alterSnapGesture.indexOf('relax') !== -1; const constrained = config.snapConstraint && !relaxed; @@ -1183,9 +1214,13 @@ const axisAlignedBoundingBoxShape = shapesToBox => { }; const resizeGroup = (shapes, selectedShapes, elements) => { - if (!elements.length) return { shapes, selectedShapes }; + if (!elements.length) { + return { shapes, selectedShapes }; + } const e = elements[0]; - if (e.subtype !== 'adHocGroup') return { shapes, selectedShapes }; + if (e.subtype !== 'adHocGroup') { + return { shapes, selectedShapes }; + } if (!e.baseAB) { return { shapes: shapes.map(s => ({ ...s, childBaseAB: null, baseLocalTransformMatrix: null })), @@ -1197,7 +1232,9 @@ const resizeGroup = (shapes, selectedShapes, elements) => { const groupScale = matrix.scale(groupScaleX, groupScaleY, 1); return { shapes: shapes.map(s => { - if (s.parent !== e.id || s.type === 'annotation') return s; + if (s.parent !== e.id || s.type === 'annotation') { + return s; + } const childBaseAB = s.childBaseAB || [s.a, s.b]; const impliedScale = matrix.scale(...childBaseAB, 1); const inverseImpliedScale = matrix.invert(impliedScale); @@ -1346,7 +1383,9 @@ const bidirectionalCursors = { }; const cursor = select((shape, draggedPrimaryShape) => { - if (!shape) return 'auto'; + if (!shape) { + return 'auto'; + } switch (shape.subtype) { case config.rotationHandleName: return 'crosshair'; diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/matrix.js b/x-pack/plugins/canvas/public/lib/aeroelastic/matrix.js index 53c5652c02497..ae9120c9ecd9b 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/matrix.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/matrix.js @@ -227,7 +227,9 @@ const invert = ([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]) => { } else { const recDet = 1 / det; - for (let index = 0; index < 16; index++) inv[index] *= recDet; + for (let index = 0; index < 16; index++) { + inv[index] *= recDet; + } return inv; } diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/state.js b/x-pack/plugins/canvas/public/lib/aeroelastic/state.js index 448c8b161f7c2..7922784442caf 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/state.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/state.js @@ -23,12 +23,15 @@ const selectReduce = (fun, previousValue, mapFun = d => d, logFun) => (...inputs if ( shallowEqual(argumentValues, (argumentValues = inputs.map(input => input(state)))) && value === prevValue - ) + ) { return mappedValue; + } prevValue = value; value = fun(prevValue, ...argumentValues); - if (logFun) logFun(value, argumentValues); + if (logFun) { + logFun(value, argumentValues); + } mappedValue = mapFun(value); return mappedValue; }; @@ -45,12 +48,15 @@ const select = (fun, logFun) => (...inputs) => { if ( actionId === lastActionId || shallowEqual(argumentValues, (argumentValues = inputs.map(input => input(state)))) - ) + ) { return value; + } value = fun(...argumentValues); actionId = lastActionId; - if (logFun) logFun(value, argumentValues); + if (logFun) { + logFun(value, argumentValues); + } return value; }; }; @@ -70,7 +76,9 @@ const createStore = (initialState, onChangeCallback = () => {}) => { payload: { ...payload, uid: makeUid() }, }, }); - if (!meta.silent) onChangeCallback({ type, state: currentState }, meta); + if (!meta.silent) { + onChangeCallback({ type, state: currentState }, meta); + } }; const dispatch = (type, payload) => setTimeout(() => commit(type, payload)); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic_kibana.js b/x-pack/plugins/canvas/public/lib/aeroelastic_kibana.js index 9e00538ab37d8..0363736d8b3b1 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic_kibana.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic_kibana.js @@ -16,7 +16,9 @@ export const aeroelastic = { }, createStore(initialState, onChangeCallback = () => {}, page) { - if (stores.has(page)) throw new Error('Only a single aeroelastic store per page should exist'); + if (stores.has(page)) { + throw new Error('Only a single aeroelastic store per page should exist'); + } stores.set(page, aero.state.createStore(initialState, onChangeCallback)); @@ -30,12 +32,16 @@ export const aeroelastic = { }, removeStore(page) { - if (stores.has(page)) stores.delete(page); + if (stores.has(page)) { + stores.delete(page); + } }, getStore(page) { const store = stores.get(page); - if (!store) throw new Error('An aeroelastic store should exist for page ' + page); + if (!store) { + throw new Error('An aeroelastic store should exist for page ' + page); + } return store.getCurrentState(); }, diff --git a/x-pack/plugins/canvas/public/lib/arg_helpers.js b/x-pack/plugins/canvas/public/lib/arg_helpers.js index 5640a218170e8..b674e158f3e34 100644 --- a/x-pack/plugins/canvas/public/lib/arg_helpers.js +++ b/x-pack/plugins/canvas/public/lib/arg_helpers.js @@ -23,14 +23,20 @@ const isAllowed = type => includes(allowedTypes, type); export function validateArg(value) { const type = getType(value); - if (!isAllowed(type)) throw badType(); + if (!isAllowed(type)) { + throw badType(); + } return value; } export function getSimpleArg(name, args) { - if (!args[name]) return []; + if (!args[name]) { + return []; + } return args[name].map(astVal => { - if (!isAllowed(getType(astVal))) throw badType(); + if (!isAllowed(getType(astVal))) { + throw badType(); + } return astVal; }); } diff --git a/x-pack/plugins/canvas/public/lib/element.js b/x-pack/plugins/canvas/public/lib/element.js index f2ebe9af8702b..8955002d2b414 100644 --- a/x-pack/plugins/canvas/public/lib/element.js +++ b/x-pack/plugins/canvas/public/lib/element.js @@ -19,7 +19,9 @@ export function Element(config) { // A sentence or few about what this element does this.help = config.help; - if (!config.expression) throw new Error('Element types must have a default expression'); + if (!config.expression) { + throw new Error('Element types must have a default expression'); + } this.expression = config.expression; this.filter = config.filter; this.width = config.width || 500; diff --git a/x-pack/plugins/canvas/public/lib/find_expression_type.js b/x-pack/plugins/canvas/public/lib/find_expression_type.js index c70a1ec719fe8..d6d395feade8b 100644 --- a/x-pack/plugins/canvas/public/lib/find_expression_type.js +++ b/x-pack/plugins/canvas/public/lib/find_expression_type.js @@ -36,6 +36,8 @@ export function findExpressionType(name, type) { } }, []); - if (matches.length > 1) throw new Error(`Found multiple expressions with name "${name}"`); + if (matches.length > 1) { + throw new Error(`Found multiple expressions with name "${name}"`); + } return matches[0] || null; } diff --git a/x-pack/plugins/canvas/public/lib/fullscreen.js b/x-pack/plugins/canvas/public/lib/fullscreen.js index e367ae08ea851..bb9990d4f5457 100644 --- a/x-pack/plugins/canvas/public/lib/fullscreen.js +++ b/x-pack/plugins/canvas/public/lib/fullscreen.js @@ -12,6 +12,9 @@ export function setFullscreen(fullscreen, doc = document) { const bodyClassList = body.classList; const isFullscreen = bodyClassList.contains(fullscreenClass); - if (enabled && !isFullscreen) bodyClassList.add(fullscreenClass); - else if (!enabled && isFullscreen) bodyClassList.remove(fullscreenClass); + if (enabled && !isFullscreen) { + bodyClassList.add(fullscreenClass); + } else if (!enabled && isFullscreen) { + bodyClassList.remove(fullscreenClass); + } } diff --git a/x-pack/plugins/canvas/public/lib/history_provider.js b/x-pack/plugins/canvas/public/lib/history_provider.js index 65a5acc78526d..024e1f244ed91 100644 --- a/x-pack/plugins/canvas/public/lib/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/history_provider.js @@ -63,12 +63,16 @@ function wrapHistoryInstance(history) { }, getPath(path) { - if (path != null) return createPath(parsePath(path)); + if (path != null) { + return createPath(parsePath(path)); + } return createPath(this.getLocation()); }, getFullPath(path) { - if (path != null) return history.createHref(parsePath(path)); + if (path != null) { + return history.createHref(parsePath(path)); + } return history.createHref(this.getLocation()); }, @@ -82,7 +86,9 @@ function wrapHistoryInstance(history) { onChange(fn) { // if no handler fn passed, do nothing - if (fn == null) return; + if (fn == null) { + return; + } // push onChange function onto listener stack and return a function to remove it const pushedIndex = historyState.onChange.push(fn) - 1; @@ -90,7 +96,9 @@ function wrapHistoryInstance(history) { // only allow the unlisten function to be called once let called = false; return () => { - if (called) return; + if (called) { + return; + } historyState.onChange.splice(pushedIndex, 1); called = true; }; @@ -129,14 +137,18 @@ const instances = new WeakMap(); const getHistoryInstance = win => { // if no window object, use memory module - if (typeof win === 'undefined' || !win.history) return createMemoryHistory(); + if (typeof win === 'undefined' || !win.history) { + return createMemoryHistory(); + } return createHashStateHistory(); }; export const historyProvider = (win = getWindow()) => { // return cached instance if one exists const instance = instances.get(win); - if (instance) return instance; + if (instance) { + return instance; + } // create and cache wrapped history instance const historyInstance = getHistoryInstance(win); diff --git a/x-pack/plugins/canvas/public/lib/notify.js b/x-pack/plugins/canvas/public/lib/notify.js index e824868f9541f..426cf687d54e4 100644 --- a/x-pack/plugins/canvas/public/lib/notify.js +++ b/x-pack/plugins/canvas/public/lib/notify.js @@ -14,7 +14,9 @@ const getToast = (err, opts = {}) => { const { title, ...rest } = opts; let text = null; - if (title) text = errMsg; + if (title) { + text = errMsg; + } return { ...rest, diff --git a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js index f9a560f2cfb12..fb67379550b1d 100644 --- a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js +++ b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js @@ -13,7 +13,9 @@ export function parseSingleFunctionChain(filterString) { // Check if the current column is what we expect it to be. If the user changes column this will be called again, // but we don't want to run setFilter() unless we have to because it will cause a data refresh const name = get(ast, 'chain[0].function'); - if (!name) throw new Error('Could not find function name in chain'); + if (!name) { + throw new Error('Could not find function name in chain'); + } const args = mapValues(get(ast, 'chain[0].arguments'), val => { // TODO Check for literals only diff --git a/x-pack/plugins/canvas/public/lib/resolved_arg.js b/x-pack/plugins/canvas/public/lib/resolved_arg.js index 5dc83625a7387..8a9da8e466f7e 100644 --- a/x-pack/plugins/canvas/public/lib/resolved_arg.js +++ b/x-pack/plugins/canvas/public/lib/resolved_arg.js @@ -15,6 +15,8 @@ export function getValue(resolvedArg) { } export function getError(resolvedArg) { - if (getState(resolvedArg) !== 'error') return null; + if (getState(resolvedArg) !== 'error') { + return null; + } return get(resolvedArg, 'error', null); } diff --git a/x-pack/plugins/canvas/public/lib/router_provider.js b/x-pack/plugins/canvas/public/lib/router_provider.js index eac87fd51a2a7..1e0117cf2ba2f 100644 --- a/x-pack/plugins/canvas/public/lib/router_provider.js +++ b/x-pack/plugins/canvas/public/lib/router_provider.js @@ -12,7 +12,9 @@ import { historyProvider } from './history_provider'; let router; export function routerProvider(routes) { - if (router) return router; + if (router) { + return router; + } const baseRouter = createRouter(routes); const history = historyProvider(getWindow()); @@ -22,7 +24,9 @@ export function routerProvider(routes) { const getState = (name, params, state) => { // given a path, assuming params is the state - if (isPath(name)) return params || history.getLocation().state; + if (isPath(name)) { + return params || history.getLocation().state; + } return state || history.getLocation().state; }; @@ -31,7 +35,9 @@ export function routerProvider(routes) { const method = replace ? 'replace' : 'push'; // given a path, go there directly - if (isPath(name)) return history[method](currentState, name); + if (isPath(name)) { + return history[method](currentState, name); + } history[method](currentState, baseRouter.create(name, params)); }; @@ -51,8 +57,9 @@ export function routerProvider(routes) { updateLocation(name, params, state, true); }, onPathChange(fn) { - if (componentListener != null) + if (componentListener != null) { throw new Error('Only one route component listener is allowed'); + } const execOnMatch = location => { const { pathname } = location; @@ -69,7 +76,9 @@ export function routerProvider(routes) { // on path changes, fire the path change handler componentListener = history.onChange((locationObj, prevLocationObj) => { - if (locationObj.pathname !== prevLocationObj.pathname) execOnMatch(locationObj); + if (locationObj.pathname !== prevLocationObj.pathname) { + execOnMatch(locationObj); + } }); // initially fire the path change handler diff --git a/x-pack/plugins/canvas/public/lib/run_interpreter.js b/x-pack/plugins/canvas/public/lib/run_interpreter.js index 3c193130c1fe1..f9a890b77f148 100644 --- a/x-pack/plugins/canvas/public/lib/run_interpreter.js +++ b/x-pack/plugins/canvas/public/lib/run_interpreter.js @@ -21,7 +21,9 @@ import { notify } from './notify'; export function runInterpreter(ast, context = null, options = {}) { return interpretAst(ast, context) .then(renderable => { - if (getType(renderable) === 'render') return renderable; + if (getType(renderable) === 'render') { + return renderable; + } if (options.castToRender) { return runInterpreter(fromExpression('render'), renderable, { diff --git a/x-pack/plugins/canvas/public/lib/template.js b/x-pack/plugins/canvas/public/lib/template.js index 232e47e86c4a1..b7bf4c608d18d 100644 --- a/x-pack/plugins/canvas/public/lib/template.js +++ b/x-pack/plugins/canvas/public/lib/template.js @@ -26,7 +26,9 @@ export function Template(config) { this.tags = config.tags || []; this.tags.forEach(tag => { - if (!tagsRegistry.get(tag)) tagsRegistry.register(() => ({ name: tag, color: '#666666' })); + if (!tagsRegistry.get(tag)) { + tagsRegistry.register(() => ({ name: tag, color: '#666666' })); + } }); this.width = config.width || defaultWorkpad.width; diff --git a/x-pack/plugins/canvas/public/lib/time_duration.js b/x-pack/plugins/canvas/public/lib/time_duration.js index 46d73fb02100b..5c65ea3970fd3 100644 --- a/x-pack/plugins/canvas/public/lib/time_duration.js +++ b/x-pack/plugins/canvas/public/lib/time_duration.js @@ -12,10 +12,15 @@ export const timeDuration = (time, format) => { const hours = minutes / 60; const days = hours / 24; - if (format === 'days' || days >= 1) return { length: days, format: getLabel('day', days) }; - if (format === 'hours' || hours >= 1) return { length: hours, format: getLabel('hour', hours) }; - if (format === 'minutes' || minutes >= 1) + if (format === 'days' || days >= 1) { + return { length: days, format: getLabel('day', days) }; + } + if (format === 'hours' || hours >= 1) { + return { length: hours, format: getLabel('hour', hours) }; + } + if (format === 'minutes' || minutes >= 1) { return { length: seconds / 60, format: getLabel('minute', minutes) }; + } return { length: seconds, format: getLabel('second', seconds) }; }; diff --git a/x-pack/plugins/canvas/public/lib/window_error_handler.js b/x-pack/plugins/canvas/public/lib/window_error_handler.js index b0b1c14a336d6..bf97928452c71 100644 --- a/x-pack/plugins/canvas/public/lib/window_error_handler.js +++ b/x-pack/plugins/canvas/public/lib/window_error_handler.js @@ -50,7 +50,9 @@ window.canvasInitErrorHandler = () => { const isKnownError = Object.keys(knownErrors).find(errorName => { return err.constructor.name === errorName || message.indexOf(errorName) >= 0; }); - if (isKnownError) return; + if (isKnownError) { + return; + } // uncaught errors are silenced in dev mode // NOTE: react provides no way I can tell to distingish that an error came from react, it just diff --git a/x-pack/plugins/canvas/public/state/actions/elements.js b/x-pack/plugins/canvas/public/state/actions/elements.js index 20ce10f52c1d2..f45e09390ec6f 100644 --- a/x-pack/plugins/canvas/public/state/actions/elements.js +++ b/x-pack/plugins/canvas/public/state/actions/elements.js @@ -32,7 +32,9 @@ export function getSiblingContext(state, elementId, checkIndex) { // check previous index while we're still above 0 const prevContextIndex = checkIndex - 1; - if (prevContextIndex < 0) return {}; + if (prevContextIndex < 0) { + return {}; + } // walk back up to find the closest cached context available return getSiblingContext(state, elementId, prevContextIndex); @@ -40,7 +42,9 @@ export function getSiblingContext(state, elementId, checkIndex) { function getBareElement(el, includeId = false) { const props = ['position', 'expression', 'filter']; - if (includeId) return pick(el, props.concat('id')); + if (includeId) { + return pick(el, props.concat('id')); + } return cloneDeep(pick(el, props)); } @@ -59,7 +63,9 @@ export const fetchContext = createThunk( const chain = get(element, ['ast', 'chain']); const invalidIndex = chain ? index >= chain.length : true; - if (!element || !chain || invalidIndex) throw new Error(`Invalid argument index: ${index}`); + if (!element || !chain || invalidIndex) { + throw new Error(`Invalid argument index: ${index}`); + } // cache context as the previous index const contextIndex = index - 1; @@ -79,7 +85,9 @@ export const fetchContext = createThunk( // modify the ast chain passed to the interpreter const astChain = element.ast.chain.filter((exp, i) => { - if (prevContextValue != null) return i > prevContextIndex && i < index; + if (prevContextValue != null) { + return i > prevContextIndex && i < index; + } return i < index; }); @@ -194,8 +202,11 @@ export const duplicateElement = createThunk( dispatch(_duplicateElement({ pageId, element: newElement })); // refresh all elements if there's a filter, otherwise just render the new element - if (element.filter) dispatch(fetchAllRenderables()); - else dispatch(fetchRenderable(newElement)); + if (element.filter) { + dispatch(fetchAllRenderables()); + } else { + dispatch(fetchRenderable(newElement)); + } // select the new element dispatch(selectElement(newElement.id)); @@ -217,7 +228,9 @@ export const removeElements = createThunk( })); dispatch(_removeElements(elementIds, pageId)); - if (shouldRefresh) dispatch(fetchAllRenderables()); + if (shouldRefresh) { + dispatch(fetchAllRenderables()); + } } ); @@ -227,7 +240,9 @@ export const setFilter = createThunk( const _setFilter = createAction('setFilter'); dispatch(_setFilter({ filter, elementId, pageId })); - if (doRender === true) dispatch(fetchAllRenderables()); + if (doRender === true) { + dispatch(fetchAllRenderables()); + } } ); @@ -239,7 +254,9 @@ function setExpressionFn({ dispatch, getState }, expression, elementId, pageId, // read updated element from state and fetch renderable const updatedElement = getElementById(getState(), elementId, pageId); - if (doRender === true) dispatch(fetchRenderable(updatedElement)); + if (doRender === true) { + dispatch(fetchRenderable(updatedElement)); + } } const setAst = createThunk('setAst', ({ dispatch }, ast, element, pageId, doRender = true) => { @@ -281,7 +298,9 @@ export const setAstAtIndex = createThunk( const partialAst = { ...newAst, chain: newAst.chain.filter((exp, i) => { - if (contextValue) return i > contextIndex; + if (contextValue) { + return i > contextIndex; + } return i >= index; }), }; @@ -300,7 +319,9 @@ export const setAstAtIndex = createThunk( export const setArgumentAtIndex = createThunk('setArgumentAtIndex', ({ dispatch }, args) => { const { index, argName, value, valueIndex, element, pageId } = args; const selector = ['ast', 'chain', index, 'arguments', argName]; - if (valueIndex != null) selector.push(valueIndex); + if (valueIndex != null) { + selector.push(valueIndex); + } const newElement = set(element, selector, value); const newAst = get(newElement, ['ast', 'chain', index]); @@ -349,14 +370,21 @@ export const deleteArgumentAtIndex = createThunk('deleteArgumentAtIndex', ({ dis */ export const addElement = createThunk('addElement', ({ dispatch }, pageId, element) => { const newElement = { ...getDefaultElement(), ...getBareElement(element) }; - if (element.width) newElement.position.width = element.width; - if (element.height) newElement.position.height = element.height; + if (element.width) { + newElement.position.width = element.width; + } + if (element.height) { + newElement.position.height = element.height; + } const _addElement = createAction('addElement'); dispatch(_addElement({ pageId, element: newElement })); // refresh all elements if there's a filter, otherwise just render the new element - if (element.filter) dispatch(fetchAllRenderables()); - else dispatch(fetchRenderable(newElement)); + if (element.filter) { + dispatch(fetchAllRenderables()); + } else { + dispatch(fetchRenderable(newElement)); + } // select the new element dispatch(selectElement(newElement.id)); diff --git a/x-pack/plugins/canvas/public/state/actions/workpad.js b/x-pack/plugins/canvas/public/state/actions/workpad.js index f7d0052f4e77b..af9206018c297 100644 --- a/x-pack/plugins/canvas/public/state/actions/workpad.js +++ b/x-pack/plugins/canvas/public/state/actions/workpad.js @@ -23,7 +23,9 @@ export const initializeWorkpad = createThunk('initializeWorkpad', ({ dispatch }) export const addColor = createThunk('addColor', ({ dispatch, getState }, color) => { const colors = getWorkpadColors(getState()).slice(0); - if (!includes(colors, color)) colors.push(color); + if (!includes(colors, color)) { + colors.push(color); + } dispatch(setColors(colors)); }); @@ -36,6 +38,8 @@ export const setWorkpad = createThunk( ({ dispatch, type }, workpad, { loadPages = true } = {}) => { dispatch(setRefreshInterval(0)); // disable refresh interval dispatch(createAction(type)(workpad)); // set the workpad object in state - if (loadPages) dispatch(initializeWorkpad()); // load all the elements on the workpad + if (loadPages) { + dispatch(initializeWorkpad()); + } // load all the elements on the workpad } ); diff --git a/x-pack/plugins/canvas/public/state/initial_state.js b/x-pack/plugins/canvas/public/state/initial_state.js index e2e553946b308..1dd9d59609786 100644 --- a/x-pack/plugins/canvas/public/state/initial_state.js +++ b/x-pack/plugins/canvas/public/state/initial_state.js @@ -31,7 +31,9 @@ export const getInitialState = path => { }, }; - if (!path) return state; + if (!path) { + return state; + } return get(state, path); }; diff --git a/x-pack/plugins/canvas/public/state/middleware/aeroelastic.js b/x-pack/plugins/canvas/public/state/middleware/aeroelastic.js index e3f781ffe4ef6..ca50952a7acfb 100644 --- a/x-pack/plugins/canvas/public/state/middleware/aeroelastic.js +++ b/x-pack/plugins/canvas/public/state/middleware/aeroelastic.js @@ -95,7 +95,9 @@ const updateGlobalPositions = (setMultiplePositions, { shapes, gestureEnd }, uns angle: Math.round(matrixToAngle(shape.transformMatrix)), }; - if (1 / newProps.angle === -Infinity) newProps.angle = 0; // recompose.shallowEqual discerns between 0 and -0 + if (1 / newProps.angle === -Infinity) { + newProps.angle = 0; + } // recompose.shallowEqual discerns between 0 and -0 return shallowEqual(oldProps, newProps) ? null @@ -103,7 +105,9 @@ const updateGlobalPositions = (setMultiplePositions, { shapes, gestureEnd }, uns } }) .filter(identity); - if (repositionings.length) setMultiplePositions(repositionings); + if (repositionings.length) { + setMultiplePositions(repositionings); + } }; const id = element => element.id; @@ -113,7 +117,9 @@ export const aeroelastic = ({ dispatch, getState }) => { const onChangeCallback = ({ state }) => { const nextScene = state.currentScene; - if (!nextScene.gestureEnd) return; // only update redux on gesture end + if (!nextScene.gestureEnd) { + return; + } // only update redux on gesture end // TODO: check for gestureEnd on element selection // read current data out of redux @@ -130,8 +136,9 @@ export const aeroelastic = ({ dispatch, getState }) => { // set the selected element on the global store, if one element is selected const selectedShape = nextScene.selectedPrimaryShapes[0]; if (nextScene.selectedShapes.length === 1) { - if (selectedShape && selectedShape !== selectedElement) + if (selectedShape && selectedShape !== selectedElement) { dispatch(selectElement(selectedShape)); + } } else { // otherwise, clear the selected element state dispatch(selectElement(null)); @@ -188,7 +195,9 @@ export const aeroelastic = ({ dispatch, getState }) => { let lastPageRemoved = false; if (action.type === removePage.toString()) { const preRemoveState = getState(); - if (getPages(preRemoveState).length <= 1) lastPageRemoved = true; + if (getPages(preRemoveState).length <= 1) { + lastPageRemoved = true; + } aero.removeStore(action.payload); } @@ -209,7 +218,9 @@ export const aeroelastic = ({ dispatch, getState }) => { case duplicatePage.toString(): const newPage = getSelectedPage(getState()); createStore(newPage); - if (action.type === duplicatePage.toString()) dispatch(fetchAllRenderables()); + if (action.type === duplicatePage.toString()) { + dispatch(fetchAllRenderables()); + } populateWithElements(newPage); break; @@ -225,8 +236,11 @@ export const aeroelastic = ({ dispatch, getState }) => { case selectElement.toString(): // without this condition, a mouse release anywhere will trigger it, leading to selection of whatever is // underneath the pointer (maybe nothing) when the mouse is released - if (action.payload) selectShape(prevPage, action.payload); - else unselectShape(prevPage); + if (action.payload) { + selectShape(prevPage, action.payload); + } else { + unselectShape(prevPage); + } break; @@ -241,9 +255,13 @@ export const aeroelastic = ({ dispatch, getState }) => { // TODO: add a better check for elements changing, including their position, ids, etc. const shouldResetState = prevPage !== page || !shallowEqual(prevElements.map(id), elements.map(id)); - if (shouldResetState) populateWithElements(page); + if (shouldResetState) { + populateWithElements(page); + } - if (action.type !== setMultiplePositions.toString()) unselectShape(prevPage); + if (action.type !== setMultiplePositions.toString()) { + unselectShape(prevPage); + } break; } diff --git a/x-pack/plugins/canvas/public/state/middleware/app_ready.js b/x-pack/plugins/canvas/public/state/middleware/app_ready.js index af3d713d762c7..a86f67b5e1cc4 100644 --- a/x-pack/plugins/canvas/public/state/middleware/app_ready.js +++ b/x-pack/plugins/canvas/public/state/middleware/app_ready.js @@ -15,8 +15,12 @@ export const appReady = ({ dispatch, getState }) => next => action => { const state = getState(); // if app is already ready, there's nothing more to do here - if (state.app.ready) return; + if (state.app.ready) { + return; + } // check for all conditions in the state that indicate that the app is ready - if (isAppReady(state)) dispatch(readyAction()); + if (isAppReady(state)) { + dispatch(readyAction()); + } }; diff --git a/x-pack/plugins/canvas/public/state/middleware/es_persist.js b/x-pack/plugins/canvas/public/state/middleware/es_persist.js index 52e23a5d6195e..34af6b4fc8394 100644 --- a/x-pack/plugins/canvas/public/state/middleware/es_persist.js +++ b/x-pack/plugins/canvas/public/state/middleware/es_persist.js @@ -37,7 +37,9 @@ export const esPersistMiddleware = ({ getState }) => { return next => action => { // if the action is in the skipped list, do not persist - if (skippedActions.indexOf(action.type) >= 0) return next(action); + if (skippedActions.indexOf(action.type) >= 0) { + return next(action); + } // capture state before and after the action const curState = getState(); @@ -45,7 +47,9 @@ export const esPersistMiddleware = ({ getState }) => { const newState = getState(); // skips the update request if user doesn't have write permissions - if (!canUserWrite(newState)) return; + if (!canUserWrite(newState)) { + return; + } // if the workpad changed, save it to elasticsearch if (workpadChanged(curState, newState) || assetsChanged(curState, newState)) { diff --git a/x-pack/plugins/canvas/public/state/middleware/history.js b/x-pack/plugins/canvas/public/state/middleware/history.js index 2bb089a706e5f..206c86e93de91 100644 --- a/x-pack/plugins/canvas/public/state/middleware/history.js +++ b/x-pack/plugins/canvas/public/state/middleware/history.js @@ -31,7 +31,9 @@ export const historyMiddleware = ({ dispatch, getState }) => { }; } - if (!route.action) return route; + if (!route.action) { + return route; + } return { ...route, @@ -75,7 +77,9 @@ export const historyMiddleware = ({ dispatch, getState }) => { } // execute route action on pushState and popState events - if (isUrlChange) return await router.parse(pathname); + if (isUrlChange) { + return await router.parse(pathname); + } }; history.onChange(async (...args) => { @@ -114,7 +118,9 @@ export const historyMiddleware = ({ dispatch, getState }) => { const newState = getState(); // if the app is not ready, don't persist anything - if (!isAppReady(newState)) return; + if (!isAppReady(newState)) { + return; + } // if app switched from not ready to ready, replace current state // this allows the back button to work correctly all the way to first page load diff --git a/x-pack/plugins/canvas/public/state/middleware/in_flight.js b/x-pack/plugins/canvas/public/state/middleware/in_flight.js index e8b7105b43e82..2e48ee5b72621 100644 --- a/x-pack/plugins/canvas/public/state/middleware/in_flight.js +++ b/x-pack/plugins/canvas/public/state/middleware/in_flight.js @@ -23,7 +23,9 @@ export const inFlight = ({ dispatch }) => next => { } else if (isSetting) { const idx = pendingCache.indexOf(cacheKey); pendingCache.splice(idx, 1); - if (pendingCache.length === 0) dispatch(inFlightComplete()); + if (pendingCache.length === 0) { + dispatch(inFlightComplete()); + } } } diff --git a/x-pack/plugins/canvas/public/state/middleware/index.js b/x-pack/plugins/canvas/public/state/middleware/index.js index 15bea92d5e321..ffacfaa82afee 100644 --- a/x-pack/plugins/canvas/public/state/middleware/index.js +++ b/x-pack/plugins/canvas/public/state/middleware/index.js @@ -31,7 +31,8 @@ const middlewares = [ ]; // intitialize redux devtools if extension is installed -if (getWindow().__REDUX_DEVTOOLS_EXTENSION__) +if (getWindow().__REDUX_DEVTOOLS_EXTENSION__) { middlewares.push(getWindow().__REDUX_DEVTOOLS_EXTENSION__()); +} export const middleware = compose(...middlewares); diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.js b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.js index 12752ab08734a..1c99b35353e96 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.js +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.js @@ -14,7 +14,9 @@ export const workpadRefresh = ({ dispatch, getState }) => next => { let refreshInterval = 0; function updateWorkpad() { - if (refreshInterval === 0) return; + if (refreshInterval === 0) { + return; + } // check the request in flight status const inFlightActive = getInFlight(getState()); @@ -38,7 +40,9 @@ export const workpadRefresh = ({ dispatch, getState }) => next => { next(action); // when in-flight requests are finished, update the workpad after a given delay - if (action.type === inFlightComplete.toString() && refreshInterval > 0) startDelayedUpdate(); // create new update request + if (action.type === inFlightComplete.toString() && refreshInterval > 0) { + startDelayedUpdate(); + } // create new update request // This middleware creates or destroys an interval that will cause workpad elements to update if (action.type === setRefreshInterval.toString()) { @@ -49,7 +53,9 @@ export const workpadRefresh = ({ dispatch, getState }) => next => { clearTimeout(refreshTimeout); // if interval is larger than 0, start the delayed update - if (refreshInterval > 0) startDelayedUpdate(); + if (refreshInterval > 0) { + startDelayedUpdate(); + } } }; }; diff --git a/x-pack/plugins/canvas/public/state/reducers/assets.js b/x-pack/plugins/canvas/public/state/reducers/assets.js index 587f40dbe186f..9aa3cd225ac2c 100644 --- a/x-pack/plugins/canvas/public/state/reducers/assets.js +++ b/x-pack/plugins/canvas/public/state/reducers/assets.js @@ -24,7 +24,9 @@ export const assetsReducer = handleActions( [setAssetValue]: (assetState, { payload }) => { const { id, value } = payload; const asset = get(assetState, [id]); - if (!asset) throw new Error(`Can not set asset data, id not found: ${id}`); + if (!asset) { + throw new Error(`Can not set asset data, id not found: ${id}`); + } return assign(assetState, id, { value }); }, diff --git a/x-pack/plugins/canvas/public/state/reducers/elements.js b/x-pack/plugins/canvas/public/state/reducers/elements.js index e17c09639e2e9..d000e5bd8efdc 100644 --- a/x-pack/plugins/canvas/public/state/reducers/elements.js +++ b/x-pack/plugins/canvas/public/state/reducers/elements.js @@ -24,7 +24,9 @@ function assignElementProperties(workpadState, pageId, elementId, props) { element => element.id === elementId ); - if (pageIndex === -1 || elementIndex === -1) return workpadState; + if (pageIndex === -1 || elementIndex === -1) { + return workpadState; + } // remove any AST value from the element caused by https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this after a bit of time @@ -40,13 +42,21 @@ function moveElementLayer(workpadState, pageId, elementId, movement) { const from = elementIndex; const to = (function() { - if (movement < Infinity && movement > -Infinity) return elementIndex + movement; - if (movement === Infinity) return elements.length - 1; - if (movement === -Infinity) return 0; + if (movement < Infinity && movement > -Infinity) { + return elementIndex + movement; + } + if (movement === Infinity) { + return elements.length - 1; + } + if (movement === -Infinity) { + return 0; + } throw new Error('Invalid element layer movement'); })(); - if (to > elements.length - 1 || to < 0) return workpadState; + if (to > elements.length - 1 || to < 0) { + return workpadState; + } // Common const newElements = elements.slice(0); @@ -77,19 +87,25 @@ export const elementsReducer = handleActions( }, [actions.addElement]: (workpadState, { payload: { pageId, element } }) => { const pageIndex = getPageIndexById(workpadState, pageId); - if (pageIndex < 0) return workpadState; + if (pageIndex < 0) { + return workpadState; + } return push(workpadState, ['pages', pageIndex, 'elements'], element); }, [actions.duplicateElement]: (workpadState, { payload: { pageId, element } }) => { const pageIndex = getPageIndexById(workpadState, pageId); - if (pageIndex < 0) return workpadState; + if (pageIndex < 0) { + return workpadState; + } return push(workpadState, ['pages', pageIndex, 'elements'], element); }, [actions.removeElements]: (workpadState, { payload: { pageId, elementIds } }) => { const pageIndex = getPageIndexById(workpadState, pageId); - if (pageIndex < 0) return workpadState; + if (pageIndex < 0) { + return workpadState; + } const elementIndices = elementIds .map(elementId => getElementIndexById(workpadState.pages[pageIndex], elementId)) diff --git a/x-pack/plugins/canvas/public/state/reducers/pages.js b/x-pack/plugins/canvas/public/state/reducers/pages.js index 8be944f253d30..c58e078b37f9c 100644 --- a/x-pack/plugins/canvas/public/state/reducers/pages.js +++ b/x-pack/plugins/canvas/public/state/reducers/pages.js @@ -12,7 +12,9 @@ import { getDefaultPage } from '../defaults'; import * as actions from '../actions/pages'; function setPageIndex(workpadState, index) { - if (index < 0 || !workpadState.pages[index]) return workpadState; + if (index < 0 || !workpadState.pages[index]) { + return workpadState; + } return set(workpadState, 'page', index); } @@ -52,7 +54,9 @@ export const pagesReducer = handleActions( const srcPage = workpadState.pages.find(page => page.id === payload); // if the page id is invalid, don't change the state - if (!srcPage) return workpadState; + if (!srcPage) { + return workpadState; + } const srcIndex = workpadState.pages.indexOf(srcPage); const newPageIndex = srcIndex + 1; @@ -86,10 +90,14 @@ export const pagesReducer = handleActions( const newIndex = pageIndex + position; // TODO: do something better when given an invalid page id - if (pageIndex < 0) return workpadState; + if (pageIndex < 0) { + return workpadState; + } // don't move pages past the first or last position - if (newIndex < 0 || newIndex >= workpadState.pages.length) return workpadState; + if (newIndex < 0 || newIndex >= workpadState.pages.length) { + return workpadState; + } // remove and re-insert the page const page = { ...workpadState.pages[pageIndex] }; @@ -118,7 +126,9 @@ export const pagesReducer = handleActions( const newSelectedPage = curIndex >= delIndex ? curIndex - 1 : curIndex; // if we removed the only page, create a new empty one - if (wasOnlyPage) newState = addPage(newState); + if (wasOnlyPage) { + newState = addPage(newState); + } if (wasOnlyPage || wasSelected) { // if we removed the only page or the selected one, select the first one diff --git a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js index 7404ece39136a..93c674a478619 100644 --- a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js @@ -30,13 +30,19 @@ import { flushContext, flushContextAfterIndex } from '../actions/elements'; */ function _getState(hasError, loading) { - if (hasError) return 'error'; - if (Boolean(loading)) return 'pending'; + if (hasError) { + return 'error'; + } + if (Boolean(loading)) { + return 'pending'; + } return 'ready'; } function _getValue(hasError, value, oldVal) { - if (hasError || value == null) return oldVal && oldVal.value; + if (hasError || value == null) { + return oldVal && oldVal.value; + } return value; } @@ -52,7 +58,9 @@ function getContext(value, loading = false, oldVal = null) { function getFullPath(path) { const isArray = Array.isArray(path); const isString = typeof path === 'string'; - if (!isArray && !isString) throw new Error(`Resolved argument path is invalid: ${path}`); + if (!isArray && !isString) { + throw new Error(`Resolved argument path is invalid: ${path}`); + } return prepend(path, 'resolvedArgs'); } @@ -108,12 +116,15 @@ export const resolvedArgsReducer = handleActions( const expressionContext = get(transientState, getFullPath([elementId, 'expressionContext'])); // if there is not existing context, there's nothing to do here - if (!expressionContext) return transientState; + if (!expressionContext) { + return transientState; + } return Object.keys(expressionContext).reduce((state, indexKey) => { const indexAsNum = parseInt(indexKey, 10); - if (indexAsNum >= index) + if (indexAsNum >= index) { return del(state, getFullPath([elementId, 'expressionContext', indexKey])); + } return state; }, transientState); diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.js b/x-pack/plugins/canvas/public/state/selectors/workpad.js index 1e767b847c460..3e291d68bc224 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.js +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.js @@ -91,30 +91,42 @@ export function getSelectedElement(state) { export function getElements(state, pageId, withAst = true) { const id = pageId || getSelectedPage(state); - if (!id) return []; + if (!id) { + return []; + } const page = getPageById(state, id); const elements = get(page, 'elements'); - if (!elements) return []; + if (!elements) { + return []; + } // explicitely strip the ast, basically a fix for corrupted workpads // due to https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this once it's been in the wild a bit - if (!withAst) return elements.map(el => omit(el, ['ast'])); + if (!withAst) { + return elements.map(el => omit(el, ['ast'])); + } return elements.map(appendAst); } export function getElementById(state, id, pageId) { const element = getElements(state, pageId, []).find(el => el.id === id); - if (element) return appendAst(element); + if (element) { + return appendAst(element); + } } export function getResolvedArgs(state, elementId, path) { - if (!elementId) return; + if (!elementId) { + return; + } const args = get(state, ['transient', 'resolvedArgs', elementId]); - if (path) return get(args, path); + if (path) { + return get(args, path); + } return args; } diff --git a/x-pack/plugins/canvas/public/state/store.js b/x-pack/plugins/canvas/public/state/store.js index f8d548e335de8..760e7a8609978 100644 --- a/x-pack/plugins/canvas/public/state/store.js +++ b/x-pack/plugins/canvas/public/state/store.js @@ -12,9 +12,13 @@ import { getRootReducer } from './reducers'; let store; export function createStore(initialState) { - if (typeof store !== 'undefined') throw new Error('Redux store can only be initialized once'); + if (typeof store !== 'undefined') { + throw new Error('Redux store can only be initialized once'); + } - if (!isPlainObject(initialState)) throw new Error('Initial state must be a plain object'); + if (!isPlainObject(initialState)) { + throw new Error('Initial state must be a plain object'); + } const rootReducer = getRootReducer(initialState); store = createReduxStore(rootReducer, initialState, middleware); diff --git a/x-pack/plugins/canvas/server/lib/build_es_request.js b/x-pack/plugins/canvas/server/lib/build_es_request.js index 037138cc11576..08c682d04df89 100644 --- a/x-pack/plugins/canvas/server/lib/build_es_request.js +++ b/x-pack/plugins/canvas/server/lib/build_es_request.js @@ -7,9 +7,13 @@ import { buildBoolArray } from './build_bool_array'; export function buildESRequest(esRequest, canvasQuery) { - if (canvasQuery.size) esRequest = { ...esRequest, size: canvasQuery.size }; + if (canvasQuery.size) { + esRequest = { ...esRequest, size: canvasQuery.size }; + } - if (canvasQuery.and) esRequest.body.query.bool.must = buildBoolArray(canvasQuery.and); + if (canvasQuery.and) { + esRequest.body.query.bool.must = buildBoolArray(canvasQuery.and); + } return esRequest; } diff --git a/x-pack/plugins/canvas/server/lib/filters.js b/x-pack/plugins/canvas/server/lib/filters.js index 5e4c2c64845c6..afa58c7ee30c2 100644 --- a/x-pack/plugins/canvas/server/lib/filters.js +++ b/x-pack/plugins/canvas/server/lib/filters.js @@ -9,7 +9,9 @@ */ export function time(filter) { - if (!filter.column) throw new Error('column is required for Elasticsearch range filters'); + if (!filter.column) { + throw new Error('column is required for Elasticsearch range filters'); + } return { range: { [filter.column]: { gte: filter.from, lte: filter.to }, diff --git a/x-pack/plugins/canvas/server/lib/get_es_filter.js b/x-pack/plugins/canvas/server/lib/get_es_filter.js index ccc296bc550f9..e8a4d704118e8 100644 --- a/x-pack/plugins/canvas/server/lib/get_es_filter.js +++ b/x-pack/plugins/canvas/server/lib/get_es_filter.js @@ -14,7 +14,9 @@ import * as filters from './filters'; export function getESFilter(filter) { - if (!filters[filter.type]) throw new Error(`Unknown filter type: ${filter.type}`); + if (!filters[filter.type]) { + throw new Error(`Unknown filter type: ${filter.type}`); + } try { return filters[filter.type](filter); diff --git a/x-pack/plugins/canvas/server/lib/normalize_type.js b/x-pack/plugins/canvas/server/lib/normalize_type.js index 7dd20b94096ba..be2deeecc9a21 100644 --- a/x-pack/plugins/canvas/server/lib/normalize_type.js +++ b/x-pack/plugins/canvas/server/lib/normalize_type.js @@ -26,6 +26,8 @@ export function normalizeType(type) { const normalizedType = Object.keys(normalTypes).find(t => normalTypes[t].includes(type)); - if (normalizedType) return normalizedType; + if (normalizedType) { + return normalizedType; + } throw new Error(`Canvas does not yet support type: ${type}`); } diff --git a/x-pack/plugins/canvas/server/routes/es_fields/get_es_field_types.js b/x-pack/plugins/canvas/server/routes/es_fields/get_es_field_types.js index 8e454a595f99c..36f7399ecd031 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/get_es_field_types.js +++ b/x-pack/plugins/canvas/server/routes/es_fields/get_es_field_types.js @@ -13,11 +13,15 @@ export function getESFieldTypes(index, fields, elasticsearchClient) { fields: fields || '*', }; - if (fields && fields.length === 0) return Promise.resolve({}); + if (fields && fields.length === 0) { + return Promise.resolve({}); + } return elasticsearchClient('fieldCaps', config).then(resp => { return mapValues(resp.fields, types => { - if (keys(types).length > 1) return 'conflict'; + if (keys(types).length > 1) { + return 'conflict'; + } try { return normalizeType(keys(types)[0]); diff --git a/x-pack/plugins/canvas/server/routes/es_fields/index.js b/x-pack/plugins/canvas/server/routes/es_fields/index.js index 8c6b53fb2610b..235b2b0bc69e3 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/index.js +++ b/x-pack/plugins/canvas/server/routes/es_fields/index.js @@ -16,7 +16,9 @@ export function esFields(server) { path: '/api/canvas/es_fields', handler: function(request, h) { const { index, fields } = request.query; - if (!index) return h.response({ error: '"index" query is required' }).code(400); + if (!index) { + return h.response({ error: '"index" query is required' }).code(400); + } return getESFieldTypes(index, fields, partial(callWithRequest, request)); }, diff --git a/x-pack/plugins/canvas/server/routes/workpad.js b/x-pack/plugins/canvas/server/routes/workpad.js index e873f99efa74f..8042a82aedbd6 100644 --- a/x-pack/plugins/canvas/server/routes/workpad.js +++ b/x-pack/plugins/canvas/server/routes/workpad.js @@ -14,16 +14,25 @@ export function workpad(server) { const routePrefix = API_ROUTE_WORKPAD; function formatResponse(resp) { - if (resp.isBoom) return resp; // can't wrap it if it's already a boom error + if (resp.isBoom) { + return resp; + } // can't wrap it if it's already a boom error - if (resp instanceof esErrors['400']) return boom.badRequest(resp); + if (resp instanceof esErrors['400']) { + return boom.badRequest(resp); + } - if (resp instanceof esErrors['401']) return boom.unauthorized(); + if (resp instanceof esErrors['401']) { + return boom.unauthorized(); + } - if (resp instanceof esErrors['403']) + if (resp instanceof esErrors['403']) { return boom.forbidden("Sorry, you don't have access to that"); + } - if (resp instanceof esErrors['404']) return boom.boomify(resp, { statusCode: 404 }); + if (resp instanceof esErrors['404']) { + return boom.boomify(resp, { statusCode: 404 }); + } return resp; } @@ -31,7 +40,9 @@ export function workpad(server) { function createWorkpad(req, id) { const savedObjectsClient = req.getSavedObjectsClient(); - if (!req.payload) return Promise.resolve(boom.badRequest('A workpad payload is required')); + if (!req.payload) { + return Promise.resolve(boom.badRequest('A workpad payload is required')); + } const now = new Date().toISOString(); return savedObjectsClient.create( diff --git a/x-pack/plugins/canvas/server/usage/collector.js b/x-pack/plugins/canvas/server/usage/collector.js index a73ab069638b0..b2ebe1f333bea 100644 --- a/x-pack/plugins/canvas/server/usage/collector.js +++ b/x-pack/plugins/canvas/server/usage/collector.js @@ -20,7 +20,9 @@ const collectFns = (ast, cb) => { // recurse the argumetns and update the set along the way Object.keys(cArguments).forEach(argName => { cArguments[argName].forEach(subAst => { - if (subAst != null) collectFns(subAst, cb); + if (subAst != null) { + collectFns(subAst, cb); + } }); }); }); @@ -29,7 +31,9 @@ const collectFns = (ast, cb) => { export function handleResponse({ hits }) { const workpadDocs = get(hits, 'hits', null); - if (workpadDocs == null) return; + if (workpadDocs == null) { + return; + } const functionSet = new Set(); @@ -142,7 +146,9 @@ export function registerCanvasUsageCollector(server) { }; const esResponse = await callCluster('search', searchParams); - if (get(esResponse, 'hits.hits.length') > 0) return handleResponse(esResponse); + if (get(esResponse, 'hits.hits.length') > 0) { + return handleResponse(esResponse); + } }, }); diff --git a/x-pack/plugins/canvas/tasks/helpers/webpack.plugins.js b/x-pack/plugins/canvas/tasks/helpers/webpack.plugins.js index e87ee70bdc9cc..4204761af9dba 100644 --- a/x-pack/plugins/canvas/tasks/helpers/webpack.plugins.js +++ b/x-pack/plugins/canvas/tasks/helpers/webpack.plugins.js @@ -61,10 +61,15 @@ export function getWebpackConfig({ devtool, watch } = {}) { // bails on error, including loader errors // see https://github.com/webpack/webpack/issues/708, which does not fix loader errors this.hooks.done.tapPromise('LoaderFailHandlerPlugin', async stats => { - if (!stats.hasErrors()) return; + if (!stats.hasErrors()) { + return; + } const errorMessage = stats.toString('errors-only'); - if (watch) console.error(errorMessage); - else throw new Error(errorMessage); + if (watch) { + console.error(errorMessage); + } else { + throw new Error(errorMessage); + } }); }, new CopyWebpackPlugin([ diff --git a/x-pack/plugins/canvas/tasks/test.js b/x-pack/plugins/canvas/tasks/test.js index df9aecd9dc398..9857e9c774e06 100644 --- a/x-pack/plugins/canvas/tasks/test.js +++ b/x-pack/plugins/canvas/tasks/test.js @@ -12,8 +12,12 @@ export default function testTasks(gulp, { mocha }) { function runMocha(globs, { withEnzyme = false, withDOM = false } = {}) { const requires = [join(canvasRoot, 'tasks/helpers/babelhook')]; - if (withDOM) requires.push(join(canvasRoot, 'tasks/helpers/dom_setup')); - if (withEnzyme) requires.push(join(canvasRoot, 'tasks/helpers/enzyme_setup')); + if (withDOM) { + requires.push(join(canvasRoot, 'tasks/helpers/dom_setup')); + } + if (withEnzyme) { + requires.push(join(canvasRoot, 'tasks/helpers/enzyme_setup')); + } return gulp.src(globs, { read: false }).pipe( mocha({