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

[Alerting UI] Replaced AlertsContextProvider with KibanaContextProvider and exposed components in API #84604

Merged
Merged
Show file tree
Hide file tree
Changes from 18 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
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
AlertConditionsGroup,
AlertTypeModel,
AlertTypeParamsExpressionProps,
AlertsContextValue,
} from '../../../../plugins/triggers_actions_ui/public';
import {
AlwaysFiringParams,
Expand Down Expand Up @@ -65,7 +64,7 @@ const DEFAULT_THRESHOLDS: AlwaysFiringParams['thresholds'] = {
};

export const AlwaysFiringExpression: React.FunctionComponent<
AlertTypeParamsExpressionProps<AlwaysFiringParams, AlertsContextValue>
AlertTypeParamsExpressionProps<AlwaysFiringParams>
> = ({ alertParams, setAlertParams, actionGroups, defaultActionGroupId }) => {
const {
instances = DEFAULT_INSTANCES_TO_GENERATE,
Expand Down
47 changes: 14 additions & 33 deletions x-pack/examples/alerting_example/public/components/create_alert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,27 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { useState } from 'react';
import React, { useMemo, useState } from 'react';

import { EuiIcon, EuiFlexItem, EuiCard, EuiFlexGroup } from '@elastic/eui';

import { AlertsContextProvider, AlertAdd } from '../../../../plugins/triggers_actions_ui/public';
import { AlertingExampleComponentParams } from '../application';
import { ALERTING_EXAMPLE_APP_ID } from '../../common/constants';

export const CreateAlert = ({
http,
triggersActionsUi,
charts,
uiSettings,
docLinks,
data,
toastNotifications,
capabilities,
}: AlertingExampleComponentParams) => {
export const CreateAlert = ({ triggersActionsUi }: AlertingExampleComponentParams) => {
const [alertFlyoutVisible, setAlertFlyoutVisibility] = useState<boolean>(false);

const AddAlertFlyout = useMemo(
() =>
triggersActionsUi.getAddAlertFlyout({
consumer: ALERTING_EXAMPLE_APP_ID,
addFlyoutVisible: alertFlyoutVisible,
setAddFlyoutVisibility: setAlertFlyoutVisibility,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[alertFlyoutVisible]
);

return (
<EuiFlexGroup>
<EuiFlexItem grow={false}>
Expand All @@ -34,27 +35,7 @@ export const CreateAlert = ({
onClick={() => setAlertFlyoutVisibility(true)}
/>
</EuiFlexItem>
<EuiFlexItem>
<AlertsContextProvider
value={{
http,
actionTypeRegistry: triggersActionsUi.actionTypeRegistry,
alertTypeRegistry: triggersActionsUi.alertTypeRegistry,
toastNotifications,
uiSettings,
docLinks,
charts,
dataFieldsFormats: data.fieldFormats,
capabilities,
}}
>
<AlertAdd
consumer={ALERTING_EXAMPLE_APP_ID}
addFlyoutVisible={alertFlyoutVisible}
setAddFlyoutVisibility={setAlertFlyoutVisibility}
/>
</AlertsContextProvider>
</EuiFlexItem>
<EuiFlexItem>{AddAlertFlyout}</EuiFlexItem>
</EuiFlexGroup>
);
};
20 changes: 18 additions & 2 deletions x-pack/plugins/apm/public/application/application.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ import { createMemoryHistory } from 'history';
import { Observable } from 'rxjs';
import { AppMountParameters, CoreStart, HttpSetup } from 'src/core/public';
import { mockApmPluginContextValue } from '../context/apm_plugin/mock_apm_plugin_context';
import { ApmPluginSetupDeps } from '../plugin';
import { ApmPluginSetupDeps, ApmPluginStartDeps } from '../plugin';
import { createCallApmApi } from '../services/rest/createCallApmApi';
import { renderApp } from './';
import { disableConsoleWarning } from '../utils/testHelpers';
import { dataPluginMock } from 'src/plugins/data/public/mocks';
import { embeddablePluginMock } from 'src/plugins/embeddable/public/mocks';

jest.mock('../services/rest/index_pattern', () => ({
createStaticIndexPattern: () => Promise.resolve(undefined),
Expand Down Expand Up @@ -55,6 +57,19 @@ describe('renderApp', () => {
history: createMemoryHistory(),
setHeaderActionMenu: () => {},
};

const data = dataPluginMock.createStartContract();
const embeddable = embeddablePluginMock.createStartContract();
const startDeps = {
triggersActionsUi: {
actionTypeRegistry: {},
alertTypeRegistry: {},
getAddAlertFlyout: jest.fn(),
getEditAlertFlyout: jest.fn(),
},
data,
embeddable,
};
jest.spyOn(window, 'scrollTo').mockReturnValueOnce(undefined);
createCallApmApi((core.http as unknown) as HttpSetup);

Expand All @@ -75,7 +90,8 @@ describe('renderApp', () => {
(core as unknown) as CoreStart,
(plugins as unknown) as ApmPluginSetupDeps,
(params as unknown) as AppMountParameters,
config
config,
(startDeps as unknown) as ApmPluginStartDeps
);
});

Expand Down
48 changes: 21 additions & 27 deletions x-pack/plugins/apm/public/application/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
RedirectAppLinks,
useUiSetting$,
} from '../../../../../src/plugins/kibana_react/public';
import { AlertsContextProvider } from '../../../triggers_actions_ui/public';
import { routes } from '../components/app/Main/route_config';
import { ScrollToTopOnPathChange } from '../components/app/Main/ScrollToTopOnPathChange';
import {
Expand All @@ -29,7 +28,7 @@ import {
import { LicenseProvider } from '../context/license/license_context';
import { UrlParamsProvider } from '../context/url_params_context/url_params_context';
import { useBreadcrumbs } from '../hooks/use_breadcrumbs';
import { ApmPluginSetupDeps } from '../plugin';
import { ApmPluginSetupDeps, ApmPluginStartDeps } from '../plugin';
import { createCallApmApi } from '../services/rest/createCallApmApi';
import { createStaticIndexPattern } from '../services/rest/index_pattern';
import { setHelpExtension } from '../setHelpExtension';
Expand Down Expand Up @@ -66,38 +65,29 @@ function App() {

export function ApmAppRoot({
apmPluginContextValue,
startDeps,
}: {
apmPluginContextValue: ApmPluginContextValue;
startDeps: ApmPluginStartDeps;
}) {
const { appMountParameters, core, plugins } = apmPluginContextValue;
const { appMountParameters, core } = apmPluginContextValue;
const { history } = appMountParameters;
const i18nCore = core.i18n;

return (
<RedirectAppLinks application={core.application}>
<ApmPluginContext.Provider value={apmPluginContextValue}>
<AlertsContextProvider
value={{
http: core.http,
docLinks: core.docLinks,
capabilities: core.application.capabilities,
toastNotifications: core.notifications.toasts,
actionTypeRegistry: plugins.triggersActionsUi.actionTypeRegistry,
alertTypeRegistry: plugins.triggersActionsUi.alertTypeRegistry,
}}
>
<KibanaContextProvider services={{ ...core, ...plugins }}>
<i18nCore.Context>
<Router history={history}>
<UrlParamsProvider>
<LicenseProvider>
<App />
</LicenseProvider>
</UrlParamsProvider>
</Router>
</i18nCore.Context>
</KibanaContextProvider>
</AlertsContextProvider>
<KibanaContextProvider services={{ ...core, ...startDeps }}>
<i18nCore.Context>
<Router history={history}>
<UrlParamsProvider>
<LicenseProvider>
<App />
</LicenseProvider>
</UrlParamsProvider>
</Router>
</i18nCore.Context>
</KibanaContextProvider>
</ApmPluginContext.Provider>
</RedirectAppLinks>
);
Expand All @@ -111,7 +101,8 @@ export const renderApp = (
core: CoreStart,
setupDeps: ApmPluginSetupDeps,
appMountParameters: AppMountParameters,
config: ConfigSchema
config: ConfigSchema,
startDeps: ApmPluginStartDeps
) => {
const { element } = appMountParameters;
const apmPluginContextValue = {
Expand All @@ -133,7 +124,10 @@ export const renderApp = (
});

ReactDOM.render(
<ApmAppRoot apmPluginContextValue={apmPluginContextValue} />,
<ApmAppRoot
apmPluginContextValue={apmPluginContextValue}
startDeps={startDeps}
/>,
Comment on lines +127 to +130
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally startDeps is part of the plugin context value, similar to plugins. We've not named the properties here appropriately but we'll change that separately from this PR.

Copy link
Contributor Author

@YulNaumenko YulNaumenko Dec 7, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds right for me, I had the similar thoughts, but decided not to modify your plugin context. Are you OK to have it for this PR as it is currently implemented?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing.

element
);
return () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,38 @@
* 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 from 'react';
import React, { useMemo } from 'react';
import { useKibana } from '../../../../../../../src/plugins/kibana_react/public';
import { AlertType } from '../../../../common/alert_types';
import { AlertAdd } from '../../../../../triggers_actions_ui/public';

type AlertAddProps = React.ComponentProps<typeof AlertAdd>;
import { TriggersAndActionsUIPublicPluginStart } from '../../../../../triggers_actions_ui/public';

interface Props {
addFlyoutVisible: AlertAddProps['addFlyoutVisible'];
setAddFlyoutVisibility: AlertAddProps['setAddFlyoutVisibility'];
addFlyoutVisible: boolean;
setAddFlyoutVisibility: React.Dispatch<React.SetStateAction<boolean>>;
alertType: AlertType | null;
}

interface KibanaDeps {
triggersActionsUi: TriggersAndActionsUIPublicPluginStart;
}

export function AlertingFlyout(props: Props) {
const { addFlyoutVisible, setAddFlyoutVisibility, alertType } = props;
return (
alertType && (
<AlertAdd
addFlyoutVisible={addFlyoutVisible}
setAddFlyoutVisibility={setAddFlyoutVisibility}
consumer="apm"
alertTypeId={alertType}
canChangeTrigger={false}
/>
)
const {
services: { triggersActionsUi },
} = useKibana<KibanaDeps>();
const AddAlertFlyout = useMemo(
() =>
alertType &&
triggersActionsUi.getAddAlertFlyout({
consumer: 'apm',
addFlyoutVisible,
setAddFlyoutVisibility,
alertTypeId: alertType,
canChangeTrigger: false,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[addFlyoutVisible, alertType]
);
return <>{AddAlertFlyout}</>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why this cannot be a component that the alerting UI exports?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the code reducing prospective it sounds right to expose it as component, but our decision was to live the details of the flyout usage to the end plugin - as a result it can be without memoizations or with the own dependancies list.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the memoization is not needed?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks ok, but since it's not a component could we make the variable lowercase? Also why are we disabling exhaustive-deps? If there's a good reason for that please add a comment explaining why.

}
10 changes: 8 additions & 2 deletions x-pack/plugins/apm/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,18 @@ export class ApmPlugin implements Plugin<ApmPluginSetup, ApmPluginStart> {

async mount(params: AppMountParameters<unknown>) {
// Load application bundle and Get start services
const [{ renderApp }, [coreStart]] = await Promise.all([
const [{ renderApp }, [coreStart, corePlugins]] = await Promise.all([
import('./application'),
core.getStartServices(),
]);

return renderApp(coreStart, pluginSetupDeps, params, config);
return renderApp(
coreStart,
pluginSetupDeps,
params,
config,
corePlugins as ApmPluginStartDeps
);
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { HttpSetup } from 'kibana/public';
import { omit } from 'lodash';
import React, { useCallback, useMemo, useState } from 'react';
import {
Expand All @@ -20,6 +19,7 @@ import {
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';
import { useKibana } from '../../../../../../../src/plugins/kibana_react/public';
import { FORMATTERS } from '../../../../common/formatters';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { ValidationResult } from '../../../../../triggers_actions_ui/public/types';
Expand All @@ -35,7 +35,6 @@ interface Props {
alertInterval: string;
alertThrottle: string;
alertType: PreviewableAlertTypes;
fetch: HttpSetup['fetch'];
alertParams: { criteria: any[]; sourceId: string } & Record<string, any>;
validate: (params: any) => ValidationResult;
showNoDataResults?: boolean;
Expand All @@ -47,12 +46,13 @@ export const AlertPreview: React.FC<Props> = (props) => {
alertParams,
alertInterval,
alertThrottle,
fetch,
alertType,
validate,
showNoDataResults,
groupByDisplayName,
} = props;
const { http } = useKibana().services;

const [previewLookbackInterval, setPreviewLookbackInterval] = useState<string>('h');
const [isPreviewLoading, setIsPreviewLoading] = useState<boolean>(false);
const [previewError, setPreviewError] = useState<any | false>(false);
Expand All @@ -70,7 +70,7 @@ export const AlertPreview: React.FC<Props> = (props) => {
setPreviewError(false);
try {
const result = await getAlertPreview({
fetch,
fetch: http!.fetch,
params: {
...alertParams,
lookback: previewLookbackInterval as 'h' | 'd' | 'w' | 'M',
Expand All @@ -89,12 +89,12 @@ export const AlertPreview: React.FC<Props> = (props) => {
}, [
alertParams,
alertInterval,
fetch,
alertType,
groupByDisplayName,
previewLookbackInterval,
alertThrottle,
showNoDataResults,
http,
]);

const previewIntervalError = useMemo(() => {
Expand Down
Loading