Skip to content

Commit

Permalink
Revert "[ML] Transforms: Deprecate custom KibanaContext. (#59133)"
Browse files Browse the repository at this point in the history
This reverts commit 29975fa.
  • Loading branch information
spalger committed Mar 4, 2020
1 parent b1cb92f commit ef38287
Show file tree
Hide file tree
Showing 31 changed files with 937 additions and 3,114 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { DefaultOperator } from 'elasticsearch';

import { dictionaryToArray } from '../../../common/types/common';
import { SavedSearchQuery } from '../hooks/use_search_items';
import { SavedSearchQuery } from '../lib/kibana';

import { StepDefineExposedState } from '../sections/create_transform/components/step_define/step_define_form';
import { StepDetailsExposedState } from '../sections/create_transform/components/step_details/step_details_form';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
import React from 'react';
import { render } from '@testing-library/react';

import { KibanaContext } from '../lib/kibana';
import { createPublicShim } from '../../shim';
import { getAppProviders } from '../app_dependencies';

import { ToastNotificationText } from './toast_notification_text';

jest.mock('../../shared_imports');
jest.mock('ui/new_platform');

describe('ToastNotificationText', () => {
test('should render the text as plain text', () => {
Expand All @@ -23,7 +23,9 @@ describe('ToastNotificationText', () => {
};
const { container } = render(
<Providers>
<ToastNotificationText {...props} />
<KibanaContext.Provider value={{ initialized: false }}>
<ToastNotificationText {...props} />
</KibanaContext.Provider>
</Providers>
);
expect(container.textContent).toBe('a short text message');
Expand All @@ -37,7 +39,9 @@ describe('ToastNotificationText', () => {
};
const { container } = render(
<Providers>
<ToastNotificationText {...props} />
<KibanaContext.Provider value={{ initialized: false }}>
<ToastNotificationText {...props} />
</KibanaContext.Provider>
</Providers>
);
expect(container.textContent).toBe(
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import {

import { matchAllQuery } from '../../common';

export type SavedSearchQuery = object;

type IndexPatternId = string;
type SavedSearchId = string;

Expand Down Expand Up @@ -62,7 +60,7 @@ export function getIndexPatternIdByTitle(indexPatternTitle: string): string | un
return indexPatternCache.find(d => d?.attributes?.title === indexPatternTitle)?.id;
}

type CombinedQuery = Record<'bool', any> | object;
type CombinedQuery = Record<'bool', any> | unknown;

export function loadCurrentIndexPattern(
indexPatterns: IndexPatternsContract,
Expand All @@ -81,20 +79,17 @@ export function loadCurrentSavedSearch(savedSearches: any, savedSearchId: SavedS
function isIndexPattern(arg: any): arg is IndexPattern {
return arg !== undefined;
}

export interface SearchItems {
indexPattern: IndexPattern;
savedSearch: any;
query: any;
combinedQuery: CombinedQuery;
}

// Helper for creating the items used for searching and job creation.
export function createSearchItems(
indexPattern: IndexPattern | undefined,
savedSearch: any,
config: IUiSettingsClient
): SearchItems {
): {
indexPattern: IndexPattern;
savedSearch: any;
query: any;
combinedQuery: CombinedQuery;
} {
// query is only used by the data visualizer as it needs
// a lucene query_string.
// Using a blank query will cause match_all:{} to be used
Expand Down
17 changes: 17 additions & 0 deletions x-pack/legacy/plugins/transform/public/app/lib/kibana/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

export { getIndexPatternIdByTitle, loadIndexPatterns } from './common';
export {
useKibanaContext,
InitializedKibanaContextValue,
KibanaContext,
KibanaContextValue,
SavedSearchQuery,
RenderOnlyWithInitializedKibanaContext,
} from './kibana_context';
export { KibanaProvider } from './kibana_provider';
export { useCurrentIndexPattern } from './use_current_index_pattern';
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;
* you may not use this file except in compliance with the Elastic License.
*/

import React, { createContext, useContext, FC } from 'react';

import { IUiSettingsClient } from 'kibana/public';

import {
IndexPattern,
IndexPatternsContract,
} from '../../../../../../../../src/plugins/data/public';
import { SavedSearch } from '../../../../../../../../src/plugins/discover/public/';

interface UninitializedKibanaContextValue {
initialized: false;
}

export interface InitializedKibanaContextValue {
combinedQuery: any;
indexPatterns: IndexPatternsContract;
initialized: true;
kibanaConfig: IUiSettingsClient;
currentIndexPattern: IndexPattern;
currentSavedSearch?: SavedSearch;
}

export type KibanaContextValue = UninitializedKibanaContextValue | InitializedKibanaContextValue;

export function isKibanaContextInitialized(arg: any): arg is InitializedKibanaContextValue {
return arg.initialized;
}

export type SavedSearchQuery = object;

export const KibanaContext = createContext<KibanaContextValue>({ initialized: false });

/**
* Custom hook to get the current kibanaContext.
*
* @remarks
* This hook should only be used in components wrapped in `RenderOnlyWithInitializedKibanaContext`,
* otherwise it will throw an error when KibanaContext hasn't been initialized yet.
* In return you get the benefit of not having to check if it's been initialized in the component
* where it's used.
*
* @returns `kibanaContext`
*/
export const useKibanaContext = () => {
const kibanaContext = useContext(KibanaContext);

if (!isKibanaContextInitialized(kibanaContext)) {
throw new Error('useKibanaContext: kibanaContext not initialized');
}

return kibanaContext;
};

/**
* Wrapper component to render children only if `kibanaContext` has been initialized.
* In combination with `useKibanaContext` this avoids having to check for the initialization
* in consuming components.
*
* @returns `children` or `null` depending on whether `kibanaContext` is initialized or not.
*/
export const RenderOnlyWithInitializedKibanaContext: FC = ({ children }) => {
const kibanaContext = useContext(KibanaContext);

return isKibanaContextInitialized(kibanaContext) ? <>{children}</> : null;
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,30 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { useEffect, useState } from 'react';

import { createSavedSearchesLoader } from '../../../shared_imports';
import React, { useEffect, useState, FC } from 'react';

import { useAppDependencies } from '../../app_dependencies';

import {
createSearchItems,
getIndexPatternIdByTitle,
loadCurrentIndexPattern,
loadIndexPatterns,
loadCurrentSavedSearch,
SearchItems,
} from './common';

export const useSearchItems = (defaultSavedObjectId: string | undefined) => {
const [savedObjectId, setSavedObjectId] = useState(defaultSavedObjectId);
import { InitializedKibanaContextValue, KibanaContext, KibanaContextValue } from './kibana_context';

interface Props {
savedObjectId: string;
}

export const KibanaProvider: FC<Props> = ({ savedObjectId, children }) => {
const appDeps = useAppDependencies();
const indexPatterns = appDeps.plugins.data.indexPatterns;
const uiSettings = appDeps.core.uiSettings;
const savedObjectsClient = appDeps.core.savedObjects.client;
const savedSearches = createSavedSearchesLoader({
savedObjectsClient,
indexPatterns,
chrome: appDeps.core.chrome,
overlays: appDeps.core.overlays,
});
const savedSearches = appDeps.plugins.savedSearches.getClient();

const [searchItems, setSearchItems] = useState<SearchItems | undefined>(undefined);
const [contextValue, setContextValue] = useState<KibanaContextValue>({ initialized: false });

async function fetchSavedObject(id: string) {
await loadIndexPatterns(savedObjectsClient, indexPatterns);
Expand All @@ -53,21 +47,31 @@ export const useSearchItems = (defaultSavedObjectId: string | undefined) => {
// Just let fetchedSavedSearch stay undefined in case it doesn't exist.
}

setSearchItems(createSearchItems(fetchedIndexPattern, fetchedSavedSearch, uiSettings));
const kibanaConfig = appDeps.core.uiSettings;

const {
indexPattern: currentIndexPattern,
savedSearch: currentSavedSearch,
combinedQuery,
} = createSearchItems(fetchedIndexPattern, fetchedSavedSearch, kibanaConfig);

const kibanaContext: InitializedKibanaContextValue = {
indexPatterns,
initialized: true,
kibanaConfig,
combinedQuery,
currentIndexPattern,
currentSavedSearch,
};

setContextValue(kibanaContext);
}

useEffect(() => {
if (savedObjectId !== undefined) {
fetchSavedObject(savedObjectId);
}
// Run this only when savedObjectId changes.
fetchSavedObject(savedObjectId);
// fetchSavedObject should not be tracked.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [savedObjectId]);

return {
getIndexPatternIdByTitle,
loadIndexPatterns,
searchItems,
setSavedObjectId,
};
return <KibanaContext.Provider value={contextValue}>{children}</KibanaContext.Provider>;
};
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;
* you may not use this file except in compliance with the Elastic License.
*/

import { useContext } from 'react';

import { isKibanaContextInitialized, KibanaContext } from './kibana_context';

export const useCurrentIndexPattern = () => {
const context = useContext(KibanaContext);

if (!isKibanaContextInitialized(context)) {
throw new Error('useCurrentIndexPattern: kibanaContext not initialized');
}

return context.currentIndexPattern;
};
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,19 @@ import {
} from '@elastic/eui';

import { useApi } from '../../hooks/use_api';
import { useSearchItems } from '../../hooks/use_search_items';

import { APP_CREATE_TRANSFORM_CLUSTER_PRIVILEGES } from '../../../../common/constants';

import { useAppDependencies, useDocumentationLinks } from '../../app_dependencies';
import { TransformPivotConfig } from '../../common';
import { breadcrumbService, docTitleService, BREADCRUMB_SECTION } from '../../services/navigation';
import { PrivilegesWrapper } from '../../lib/authorization';
import {
getIndexPatternIdByTitle,
loadIndexPatterns,
KibanaProvider,
RenderOnlyWithInitializedKibanaContext,
} from '../../lib/kibana';

import { Wizard } from '../create_transform/components/wizard';

Expand Down Expand Up @@ -75,12 +80,7 @@ export const CloneTransformSection: FC<Props> = ({ match }) => {
const [transformConfig, setTransformConfig] = useState<TransformPivotConfig>();
const [errorMessage, setErrorMessage] = useState();
const [isInitialized, setIsInitialized] = useState(false);
const {
getIndexPatternIdByTitle,
loadIndexPatterns,
searchItems,
setSavedObjectId,
} = useSearchItems(undefined);
const [savedObjectId, setSavedObjectId] = useState<string | undefined>(undefined);

const fetchTransformConfig = async () => {
try {
Expand Down Expand Up @@ -169,8 +169,12 @@ export const CloneTransformSection: FC<Props> = ({ match }) => {
<pre>{JSON.stringify(errorMessage)}</pre>
</EuiCallOut>
)}
{searchItems !== undefined && isInitialized === true && transformConfig !== undefined && (
<Wizard cloneConfig={transformConfig} searchItems={searchItems} />
{savedObjectId !== undefined && isInitialized === true && transformConfig !== undefined && (
<KibanaProvider savedObjectId={savedObjectId}>
<RenderOnlyWithInitializedKibanaContext>
<Wizard cloneConfig={transformConfig} />
</RenderOnlyWithInitializedKibanaContext>
</KibanaProvider>
)}
</EuiPageContentBody>
</EuiPageContent>
Expand Down
Loading

0 comments on commit ef38287

Please sign in to comment.