Skip to content

Commit

Permalink
[ui/public/utils] Copy rarely used items to where they are consumed (#…
Browse files Browse the repository at this point in the history
…53819)

* [ui/public/utils] Copy rarely used items to where they are consumed

Closes: #52841

* sort_prefix_first 👉x-pack/legacy/plugins/kuery_autocomplete

* numeric 👉src/legacy/core_plugins/kibana/public/management

* diff_object + tests 👉ui/state_management

* function + tests 👉ui/state_management (function.js was removed!)

* key_map 👉ui/directives

* leastCommonMultiple 👉ui/vis

* string_utils 👉ui/saved_objects

* collection

* parse_interval

* it -> test

* fix CI

* fix PR comments

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
alexwizp and elasticmachine authored Jan 8, 2020
1 parent 007ea5f commit 71ff2de
Show file tree
Hide file tree
Showing 47 changed files with 756 additions and 769 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { uiModules } from 'ui/modules';
import { fatalError, toastNotifications } from 'ui/notify';
import 'ui/accessibility/kbn_ui_ace_keyboard_mode';
import { SavedObjectsClientProvider } from 'ui/saved_objects';
import { isNumeric } from 'ui/utils/numeric';
import { isNumeric } from './lib/numeric';
import { canViewInApp } from './lib/in_app_url';

import { castEsToKbnFieldTypeName } from '../../../../../../../plugins/data/public';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@
* under the License.
*/

import { partition } from 'lodash';
import { keysToCamelCaseShallow } from './case_conversion';

export function sortPrefixFirst(array: any[], prefix?: string | number, property?: string): any[] {
if (!prefix) {
return array;
}
const lowerCasePrefix = ('' + prefix).toLowerCase();
describe('keysToCamelCaseShallow', () => {
test("should convert all of an object's keys to camel case", () => {
const data = {
camelCase: 'camelCase',
'kebab-case': 'kebabCase',
snake_case: 'snakeCase',
};

const partitions = partition(array, entry => {
const value = ('' + (property ? entry[property] : entry)).toLowerCase();
return value.startsWith(lowerCasePrefix);
const result = keysToCamelCaseShallow(data);

expect(result.camelCase).toBe('camelCase');
expect(result.kebabCase).toBe('kebabCase');
expect(result.snakeCase).toBe('snakeCase');
});
return [...partitions[0], ...partitions[1]];
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* under the License.
*/

import moment from 'moment';
import { mapKeys, camelCase } from 'lodash';

export function parseInterval(interval: string): moment.Duration | null;
export function keysToCamelCaseShallow(object: Record<string, any>) {
return mapKeys(object, (value, key) => camelCase(key));
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@
*/

import { kfetch } from 'ui/kfetch';
import { keysToCamelCaseShallow } from 'ui/utils/case_conversion';
import { keysToCamelCaseShallow } from './case_conversion';

export async function findObjects(findOptions) {
const response = await kfetch({
method: 'GET',
pathname: '/api/kibana/management/saved_objects/_find',
query: findOptions,
});

return keysToCamelCaseShallow(response);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
* under the License.
*/

import _ from 'lodash';
import { isNaN } from 'lodash';

export function isNumeric(v: any): boolean {
return !_.isNaN(v) && (typeof v === 'number' || (!Array.isArray(v) && !_.isNaN(parseFloat(v))));
return !isNaN(v) && (typeof v === 'number' || (!Array.isArray(v) && !isNaN(parseFloat(v))));
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
* under the License.
*/

import { StringUtils } from 'ui/utils/string_utils';
import { i18n } from '@kbn/i18n';

const upperFirst = (str = '') => str.replace(/^./, str => str.toUpperCase());

const names = {
general: i18n.translate('kbn.management.settings.categoryNames.generalLabel', {
defaultMessage: 'General',
Expand Down Expand Up @@ -51,5 +52,5 @@ const names = {
};

export function getCategoryName(category) {
return category ? names[category] || StringUtils.upperFirst(category) : '';
return category ? names[category] || upperFirst(category) : '';
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,21 @@ import _ from 'lodash';
/**
* just a place to put feature detection checks
*/
export const supports = {
cssFilters: (function() {
const e = document.createElement('img');
const rules = ['webkitFilter', 'mozFilter', 'msFilter', 'filter'];
const test = 'grayscale(1)';
rules.forEach(function(rule) {
e.style[rule] = test;
});
export const supportsCssFilters = (function() {
const e = document.createElement('img');
const rules = ['webkitFilter', 'mozFilter', 'msFilter', 'filter'];
const test = 'grayscale(1)';

document.body.appendChild(e);
const styles = window.getComputedStyle(e);
const can = _(styles)
.pick(rules)
.includes(test);
document.body.removeChild(e);
rules.forEach(function(rule) {
e.style[rule] = test;
});

return can;
})(),
};
document.body.appendChild(e);
const styles = window.getComputedStyle(e);
const can = _(styles)
.pick(rules)
.includes(test);
document.body.removeChild(e);

return can;
})();
4 changes: 2 additions & 2 deletions src/legacy/core_plugins/tile_map/public/tile_map_type.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import React from 'react';
import { i18n } from '@kbn/i18n';

import { supports } from 'ui/utils/supports';
import { Schemas } from 'ui/vis/editors/default/schemas';
import { colorSchemas } from 'ui/vislib/components/color/truncated_colormaps';
import { convertToGeoJson } from 'ui/vis/map/convert_to_geojson';
Expand All @@ -29,6 +28,7 @@ import { createTileMapVisualization } from './tile_map_visualization';
import { Status } from '../../visualizations/public';
import { TileMapOptions } from './components/tile_map_options';
import { MapTypes } from './map_types';
import { supportsCssFilters } from './css_filters';

export function createTileMapTypeDefinition(dependencies) {
const CoordinateMapsVisualization = createTileMapVisualization(dependencies);
Expand All @@ -44,7 +44,7 @@ export function createTileMapTypeDefinition(dependencies) {
defaultMessage: 'Plot latitude and longitude coordinates on a map',
}),
visConfig: {
canDesaturate: !!supports.cssFilters,
canDesaturate: Boolean(supportsCssFilters),
defaults: {
colorSchema: 'Yellow to Red',
mapType: 'Scaled Circle Markers',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@

import _ from 'lodash';
import rison from 'rison-node';
import { keyMap } from 'ui/utils/key_map';
import { uiModules } from 'ui/modules';
import 'ui/directives/input_focus';
import 'ui/directives/paginate';
import savedObjectFinderTemplate from './saved_object_finder.html';
import { savedSheetLoader } from '../services/saved_sheets';
import { keyMap } from 'ui/directives/key_map';

const module = uiModules.get('kibana');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
* under the License.
*/

import { parseInterval } from 'ui/utils/parse_interval';
import { GTE_INTERVAL_RE } from '../../common/interval_regexp';
import { i18n } from '@kbn/i18n';
import { parseInterval } from '../../../../../plugins/data/public';

export function validateInterval(bounds, panel, maxBuckets) {
const { interval } = panel;
Expand Down
36 changes: 36 additions & 0 deletions src/legacy/server/status/lib/case_conversion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { keysToSnakeCaseShallow } from './case_conversion';

describe('keysToSnakeCaseShallow', () => {
test("should convert all of an object's keys to snake case", () => {
const data = {
camelCase: 'camel_case',
'kebab-case': 'kebab_case',
snake_case: 'snake_case',
};

const result = keysToSnakeCaseShallow(data);

expect(result.camel_case).toBe('camel_case');
expect(result.kebab_case).toBe('kebab_case');
expect(result.snake_case).toBe('snake_case');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,8 @@
* under the License.
*/

import _ from 'lodash';
import { mapKeys, snakeCase } from 'lodash';

export function keysToSnakeCaseShallow(object: Record<string, any>) {
return _.mapKeys(object, (value, key) => {
return _.snakeCase(key);
});
}

export function keysToCamelCaseShallow(object: Record<string, any>) {
return _.mapKeys(object, (value, key) => {
return _.camelCase(key);
});
return mapKeys(object, (value, key) => snakeCase(key));
}
2 changes: 1 addition & 1 deletion src/legacy/server/status/lib/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import os from 'os';
import v8 from 'v8';
import { get, isObject, merge } from 'lodash';
import { keysToSnakeCaseShallow } from '../../../utils/case_conversion';
import { keysToSnakeCaseShallow } from './case_conversion';
import { getAllStats as cGroupStats } from './cgroup';
import { getOSInfo } from './get_os_info';

Expand Down
File renamed without changes.
5 changes: 3 additions & 2 deletions src/legacy/ui/public/directives/watch_multi/watch_multi.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

import _ from 'lodash';
import { uiModules } from '../../modules';
import { callEach } from '../../utils/function';

export function watchMultiDecorator($provide) {
$provide.decorator('$rootScope', function($delegate) {
Expand Down Expand Up @@ -112,7 +111,9 @@ export function watchMultiDecorator($provide) {
)
);

return _.partial(callEach, unwatchers);
return function() {
unwatchers.forEach(listener => listener());
};
};

function normalizeExpression($scope, expr) {
Expand Down
63 changes: 63 additions & 0 deletions src/legacy/ui/public/indexed_array/helpers/organize_by.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { groupBy } from 'lodash';
import { organizeBy } from './organize_by';

describe('organizeBy', () => {
test('it works', () => {
const col = [
{
name: 'one',
roles: ['user', 'admin', 'owner'],
},
{
name: 'two',
roles: ['user'],
},
{
name: 'three',
roles: ['user'],
},
{
name: 'four',
roles: ['user', 'admin'],
},
];

const resp = organizeBy(col, 'roles');
expect(resp).toHaveProperty('user');
expect(resp.user.length).toBe(4);

expect(resp).toHaveProperty('admin');
expect(resp.admin.length).toBe(2);

expect(resp).toHaveProperty('owner');
expect(resp.owner.length).toBe(1);
});

test('behaves just like groupBy in normal scenarios', () => {
const col = [{ name: 'one' }, { name: 'two' }, { name: 'three' }, { name: 'four' }];

const orgs = organizeBy(col, 'name');
const groups = groupBy(col, 'name');

expect(orgs).toEqual(groups);
});
});
61 changes: 61 additions & 0 deletions src/legacy/ui/public/indexed_array/helpers/organize_by.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { each, isFunction } from 'lodash';

/**
* Like _.groupBy, but allows specifying multiple groups for a
* single object.
*
* organizeBy([{ a: [1, 2, 3] }, { b: true, a: [1, 4] }], 'a')
* // Object {1: Array[2], 2: Array[1], 3: Array[1], 4: Array[1]}
*
* _.groupBy([{ a: [1, 2, 3] }, { b: true, a: [1, 4] }], 'a')
* // Object {'1,2,3': Array[1], '1,4': Array[1]}
*
* @param {array} collection - the list of values to organize
* @param {Function} callback - either a property name, or a callback.
* @return {object}
*/
export function organizeBy(collection: object[], callback: ((obj: object) => string) | string) {
const buckets: { [key: string]: object[] } = {};

function add(key: string, obj: object) {
if (!buckets[key]) {
buckets[key] = [];
}
buckets[key].push(obj);
}

each(collection, (obj: Record<string, any>) => {
const keys = isFunction(callback) ? callback(obj) : obj[callback];

if (!Array.isArray(keys)) {
add(keys, obj);
return;
}

let length = keys.length;
while (length-- > 0) {
add(keys[length], obj);
}
});

return buckets;
}
Loading

0 comments on commit 71ff2de

Please sign in to comment.