Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Move nested property utilities and url state to packages #147912

Merged
merged 14 commits into from
Dec 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -1071,4 +1071,6 @@ x-pack/packages/ml/agg_utils @elastic/ml-ui
x-pack/packages/ml/aiops_components @elastic/ml-ui
x-pack/packages/ml/aiops_utils @elastic/ml-ui
x-pack/packages/ml/is_populated_object @elastic/ml-ui
x-pack/packages/ml/nested_property @elastic/ml-ui
x-pack/packages/ml/string_hash @elastic/ml-ui
x-pack/packages/ml/url_state @elastic/ml-ui
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,9 @@
"@kbn/mapbox-gl": "link:packages/kbn-mapbox-gl",
"@kbn/ml-agg-utils": "link:x-pack/packages/ml/agg_utils",
"@kbn/ml-is-populated-object": "link:x-pack/packages/ml/is_populated_object",
"@kbn/ml-nested-property": "link:x-pack/packages/ml/nested_property",
"@kbn/ml-string-hash": "link:x-pack/packages/ml/string_hash",
"@kbn/ml-url-state": "link:x-pack/packages/ml/url_state",
"@kbn/monaco": "link:packages/kbn-monaco",
"@kbn/osquery-io-ts-types": "link:packages/kbn-osquery-io-ts-types",
"@kbn/plugin-discovery": "link:packages/kbn-plugin-discovery",
Expand Down
4 changes: 4 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -816,10 +816,14 @@
"@kbn/ml-agg-utils/*": ["x-pack/packages/ml/agg_utils/*"],
"@kbn/ml-is-populated-object": ["x-pack/packages/ml/is_populated_object"],
"@kbn/ml-is-populated-object/*": ["x-pack/packages/ml/is_populated_object/*"],
"@kbn/ml-nested-property": ["x-pack/packages/ml/nested_property"],
"@kbn/ml-nested-property/*": ["x-pack/packages/ml/nested_property/*"],
"@kbn/ml-plugin": ["x-pack/plugins/ml"],
"@kbn/ml-plugin/*": ["x-pack/plugins/ml/*"],
"@kbn/ml-string-hash": ["x-pack/packages/ml/string_hash"],
"@kbn/ml-string-hash/*": ["x-pack/packages/ml/string_hash/*"],
"@kbn/ml-url-state": ["x-pack/packages/ml/url_state"],
"@kbn/ml-url-state/*": ["x-pack/packages/ml/url_state/*"],
"@kbn/monaco": ["packages/kbn-monaco"],
"@kbn/monaco/*": ["packages/kbn-monaco/*"],
"@kbn/monitoring-collection-plugin": ["x-pack/plugins/monitoring_collection"],
Expand Down
3 changes: 3 additions & 0 deletions x-pack/packages/ml/nested_property/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @kbn/ml-nested-property

Provides functionality similar to lodash's get() except that it's TypeScript aware and able to infer return types.
9 changes: 9 additions & 0 deletions x-pack/packages/ml/nested_property/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export { getNestedProperty } from './src/get_nested_property';
export { setNestedProperty } from './src/set_nested_property';
12 changes: 12 additions & 0 deletions x-pack/packages/ml/nested_property/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../../..',
roots: ['<rootDir>/x-pack/packages/ml/nested_property'],
};
5 changes: 5 additions & 0 deletions x-pack/packages/ml/nested_property/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/ml-nested-property",
"owner": "@elastic/ml-ui"
}
9 changes: 9 additions & 0 deletions x-pack/packages/ml/nested_property/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@kbn/ml-nested-property",
"description": "TypeScript-aware utility functions to get/set attributes from objects.",
"author": "Machine Learning UI",
"homepage": "https://docs.elastic.dev/kibana-dev-docs/api/kbn-ml-nested-property",
"private": true,
"version": "1.0.0",
"license": "SSPL-1.0 OR Elastic License 2.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { getNestedProperty } from './object_utils';
import { getNestedProperty } from './get_nested_property';

describe('object_utils', () => {
test('getNestedProperty()', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,3 @@ export function getNestedProperty(

return o;
}

export const setNestedProperty = (obj: Record<string, any>, accessor: string, value: any) => {
let ref = obj;
const accessors = accessor.split('.');
const len = accessors.length;
for (let i = 0; i < len - 1; i++) {
const attribute = accessors[i];
if (ref[attribute] === undefined) {
ref[attribute] = {};
}

ref = ref[attribute];
}

ref[accessors[len - 1]] = value;

return obj;
};
72 changes: 72 additions & 0 deletions x-pack/packages/ml/nested_property/src/set_nested_property.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { setNestedProperty } from './set_nested_property';

describe('object_utils', () => {
test('setNestedProperty()', () => {
function getTestObj() {
return {
the: {
nested: {
value: 'the-nested-value',
},
},
};
}

function getFalseyObject() {
return {
the: {
nested: {
value: false,
},
other_nested: {
value: 0,
},
},
};
}

const test1 = setNestedProperty(getTestObj(), 'the', 'update');
expect(test1.the).toBe('update');

const test2 = setNestedProperty(getTestObj(), 'the$', 'update');
expect(test2.the$).toBe('update');

const test3 = setNestedProperty(getTestObj(), 'the$', 'the-default-value');
expect(test3.the$).toBe('the-default-value');

const test4 = setNestedProperty(getTestObj(), 'the.neSted', 'update');
expect(test4.the.neSted).toBe('update');

const test5 = setNestedProperty(getTestObj(), 'the.nested', 'update');
expect(test5.the.nested).toStrictEqual('update');

const test6 = setNestedProperty(getTestObj(), 'the.nested.vaLue', 'update');
expect(test6.the.nested.vaLue).toBe('update');

const test7 = setNestedProperty(getTestObj(), 'the.nested.value', 'update');
expect(test7.the.nested.value).toBe('update');

const test8 = setNestedProperty(getTestObj(), 'the.nested.value.didntExist', 'update');
expect(test8.the.nested.value.didntExist).toBe('update');

const test9 = setNestedProperty(
getTestObj(),
'the.nested.value.didntExist',
'the-default-value'
);
expect(test9.the.nested.value.didntExist).toBe('the-default-value');

const test10 = setNestedProperty(getFalseyObject(), 'the.nested.value', 'update');
expect(test10.the.nested.value).toBe('update');

const test11 = setNestedProperty(getFalseyObject(), 'the.other_nested.value', 'update');
expect(test11.the.other_nested.value).toBe('update');
});
});
24 changes: 24 additions & 0 deletions x-pack/packages/ml/nested_property/src/set_nested_property.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export const setNestedProperty = (obj: Record<string, any>, accessor: string, value: any) => {
darnautov marked this conversation as resolved.
Show resolved Hide resolved
let ref = obj;
const accessors = accessor.split('.');
const len = accessors.length;
for (let i = 0; i < len - 1; i++) {
const attribute = accessors[i];
if (typeof ref[attribute] !== 'object') {
ref[attribute] = {};
}

ref = ref[attribute];
}

ref[accessors[len - 1]] = value;

return obj;
};
18 changes: 18 additions & 0 deletions x-pack/packages/ml/nested_property/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": "../../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node",
"react"
]
},
"include": [
"**/*.ts",
"**/*.tsx",
],
"exclude": [
"target/**/*",
]
}
3 changes: 3 additions & 0 deletions x-pack/packages/ml/url_state/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @kbn/ml-url-state

URL state management.
19 changes: 19 additions & 0 deletions x-pack/packages/ml/url_state/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export {
isRisonSerializationRequired,
parseUrlState,
usePageUrlState,
useUrlState,
PageUrlStateService,
Provider,
UrlStateProvider,
type Accessor,
type Dictionary,
type SetUrlState,
} from './src/url_state';
12 changes: 12 additions & 0 deletions x-pack/packages/ml/url_state/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../../..',
roots: ['<rootDir>/x-pack/packages/ml/url_state'],
};
5 changes: 5 additions & 0 deletions x-pack/packages/ml/url_state/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/ml-url-state",
"owner": "@elastic/ml-ui"
}
9 changes: 9 additions & 0 deletions x-pack/packages/ml/url_state/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@kbn/ml-url-state",
"description": "Url state management utilities.",
"author": "Machine Learning UI",
"homepage": "https://docs.elastic.dev/kibana-dev-docs/api/kbn-ml-url-state",
"private": true,
"version": "1.0.0",
"license": "SSPL-1.0 OR Elastic License 2.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,25 @@ import React, {
useCallback,
useContext,
useMemo,
FC,
useRef,
useEffect,
type FC,
} from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { isEqual } from 'lodash';

import { getNestedProperty } from '@kbn/ml-nested-property';
import { decode, encode } from '@kbn/rison';
import { useHistory, useLocation } from 'react-router-dom';

import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
import { isPopulatedObject } from '@kbn/ml-is-populated-object';
import { Dictionary } from '../../../common/types/common';

import { getNestedProperty } from './object_utils';
import { MlPages } from '../../../common/constants/locator';
export interface Dictionary<TValue> {
[id: string]: TValue;
}

type Accessor = '_a' | '_g';
export type Accessor = '_a' | '_g';
export type SetUrlState = (
accessor: Accessor,
attribute: string | Dictionary<any>,
Expand All @@ -48,7 +50,7 @@ const risonSerializedParams = new Set(['_a', '_g']);
* Checks if the URL query parameter requires rison serialization.
* @param queryParam
*/
function isRisonSerializationRequired(queryParam: string): boolean {
export function isRisonSerializationRequired(queryParam: string): boolean {
return risonSerializedParams.has(queryParam);
}

Expand Down Expand Up @@ -86,7 +88,7 @@ export const urlStateStore = createContext<UrlState>({
setUrlState: () => {},
});

const { Provider } = urlStateStore;
export const { Provider } = urlStateStore;

export const UrlStateProvider: FC = ({ children }) => {
const history = useHistory();
Expand Down Expand Up @@ -183,15 +185,6 @@ export const useUrlState = (
return [urlState, setUrlState];
};

type LegacyUrlKeys = 'mlExplorerSwimlane';

export type AppStateKey =
| 'mlSelectSeverity'
| 'mlSelectInterval'
| 'mlAnomaliesTable'
| MlPages
| LegacyUrlKeys;

/**
* Service for managing URL state of particular page.
*/
Expand Down Expand Up @@ -235,16 +228,21 @@ export class PageUrlStateService<T> {
}
}

interface PageUrlState {
pageKey: string;
pageUrlState: object;
}

/**
* Hook for managing the URL state of the page.
*/
export const usePageUrlState = <PageUrlState extends object>(
pageKey: AppStateKey,
defaultState?: PageUrlState
export const usePageUrlState = <T extends PageUrlState>(
pageKey: T['pageKey'],
defaultState?: T['pageUrlState']
): [
PageUrlState,
(update: Partial<PageUrlState>, replaceState?: boolean) => void,
PageUrlStateService<PageUrlState>
T['pageUrlState'],
(update: Partial<T['pageUrlState']>, replaceState?: boolean) => void,
PageUrlStateService<T['pageUrlState']>
] => {
const [appState, setAppState] = useUrlState('_a');
const pageState = appState?.[pageKey];
Expand All @@ -255,9 +253,9 @@ export const usePageUrlState = <PageUrlState extends object>(
setCallback.current = setAppState;
}, [setAppState]);

const prevPageState = useRef<PageUrlState | undefined>();
const prevPageState = useRef<T['pageUrlState'] | undefined>();

const resultPageState: PageUrlState = useMemo(() => {
const resultPageState: T['pageUrlState'] = useMemo(() => {
const result = {
...(defaultState ?? {}),
...(pageState ?? {}),
Expand All @@ -283,7 +281,7 @@ export const usePageUrlState = <PageUrlState extends object>(
}, [pageState]);

const onStateUpdate = useCallback(
(update: Partial<PageUrlState>, replaceState?: boolean) => {
(update: Partial<T['pageUrlState']>, replaceState?: boolean) => {
if (!setCallback?.current) {
throw new Error('Callback for URL state update has not been initialized.');
}
Expand All @@ -300,7 +298,7 @@ export const usePageUrlState = <PageUrlState extends object>(
[pageKey, resultPageState]
);

const pageUrlStateService = useMemo(() => new PageUrlStateService<PageUrlState>(), []);
const pageUrlStateService = useMemo(() => new PageUrlStateService<T['pageUrlState']>(), []);

useEffect(
function updatePageUrlService() {
Expand Down
Loading