Skip to content

Commit

Permalink
[canvas] Create Notify Service; remove legacy Notify service
Browse files Browse the repository at this point in the history
  • Loading branch information
clintandrewhall committed Jun 30, 2021
1 parent e54c4a4 commit e781468
Show file tree
Hide file tree
Showing 22 changed files with 145 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,23 @@ import React, { FC } from 'react';
import { ExpressionFunction } from 'src/plugins/expressions';
import { EuiButtonEmpty } from '@elastic/eui';
import copy from 'copy-to-clipboard';
import { notifyService } from '../../services';
import { useNotifyService } from '../../services';
import { generateFunctionReference } from './generate_function_reference';

interface Props {
functionRegistry: Record<string, ExpressionFunction>;
}

export const FunctionReferenceGenerator: FC<Props> = ({ functionRegistry }) => {
const notifyService = useNotifyService();
const functionDefinitions = Object.values(functionRegistry);

const copyDocs = () => {
copy(generateFunctionReference(functionDefinitions));
notifyService
.getService()
.success(
`Please paste updated docs into '/kibana/docs/canvas/canvas-function-reference.asciidoc' and commit your changes.`,
{ title: 'Copied function docs to clipboard' }
);
notifyService.success(
`Please paste updated docs into '/kibana/docs/canvas/canvas-function-reference.asciidoc' and commit your changes.`,
{ title: 'Copied function docs to clipboard' }
);
};

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { compose, withState } from 'recompose';
import { camelCase } from 'lodash';
import { cloneSubgraphs } from '../../lib/clone_subgraphs';
import * as customElementService from '../../lib/custom_element_service';
import { withServices, WithServicesProps } from '../../services';
import { withServices, WithServicesProps, pluginServices } from '../../services';
// @ts-expect-error untyped local
import { selectToplevelNodes } from '../../state/actions/transient';
// @ts-expect-error untyped local
Expand Down Expand Up @@ -68,6 +68,7 @@ const mergeProps = (
dispatchProps: DispatchProps,
ownProps: OwnPropsWithState & WithServicesProps
): ComponentProps => {
const notifyService = pluginServices.getServices().notify;
const { pageId } = stateProps;
const { onClose, search, setCustomElements } = ownProps;

Expand All @@ -94,7 +95,7 @@ const mergeProps = (
try {
await findCustomElements();
} catch (err) {
ownProps.services.notify.error(err, {
notifyService.error(err, {
title: `Couldn't find custom elements`,
});
}
Expand All @@ -105,7 +106,7 @@ const mergeProps = (
await customElementService.remove(id);
await findCustomElements();
} catch (err) {
ownProps.services.notify.error(err, {
notifyService.error(err, {
title: `Couldn't delete custom elements`,
});
}
Expand All @@ -121,7 +122,7 @@ const mergeProps = (
});
await findCustomElements();
} catch (err) {
ownProps.services.notify.error(err, {
notifyService.error(err, {
title: `Couldn't update custom elements`,
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { withKibana } from '../../../../../../../../src/plugins/kibana_react/pub
import { OnCloseFn } from '../share_menu.component';
import { ZIP } from '../../../../../i18n/constants';
import { WithKibanaProps } from '../../../../index';
import { pluginServices } from '../../../../services';

export { OnDownloadFn, OnCopyFn } from './flyout.component';

Expand Down Expand Up @@ -95,7 +96,7 @@ export const ShareWebsiteFlyout = compose<ComponentProps, Pick<Props, 'onClose'>
unsupportedRenderers,
onClose,
onCopy: () => {
kibana.services.canvas.notify.info(strings.getCopyShareConfigMessage());
pluginServices.getServices().notify.info(strings.getCopyShareConfigMessage());
},
onDownload: (type) => {
switch (type) {
Expand All @@ -111,7 +112,7 @@ export const ShareWebsiteFlyout = compose<ComponentProps, Pick<Props, 'onClose'>
.post(`${basePath}${API_ROUTE_SHAREABLE_ZIP}`, JSON.stringify(renderedWorkpad))
.then((blob) => downloadZippedRuntime(blob.data))
.catch((err: Error) => {
kibana.services.canvas.notify.error(err, {
pluginServices.getServices().notify.error(err, {
title: strings.getShareableZipErrorTitle(workpad.name),
});
});
Expand Down
23 changes: 12 additions & 11 deletions x-pack/plugins/canvas/public/lib/download_workpad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import fileSaver from 'file-saver';
import { API_ROUTE_SHAREABLE_RUNTIME_DOWNLOAD } from '../../common/lib/constants';
import { ErrorStrings } from '../../i18n';
import { notifyService } from '../services';

// TODO: clint - convert this whole file to hooks
import { pluginServices } from '../services';

// @ts-expect-error untyped local
import * as workpadService from './workpad_service';
import { CanvasRenderedWorkpad } from '../../shareable_runtime/types';
Expand All @@ -21,7 +24,8 @@ export const downloadWorkpad = async (workpadId: string) => {
const jsonBlob = new Blob([JSON.stringify(workpad)], { type: 'application/json' });
fileSaver.saveAs(jsonBlob, `canvas-workpad-${workpad.name}-${workpad.id}.json`);
} catch (err) {
notifyService.getService().error(err, { title: strings.getDownloadFailureErrorMessage() });
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getDownloadFailureErrorMessage() });
}
};

Expand All @@ -33,9 +37,8 @@ export const downloadRenderedWorkpad = async (renderedWorkpad: CanvasRenderedWor
`canvas-embed-workpad-${renderedWorkpad.name}-${renderedWorkpad.id}.json`
);
} catch (err) {
notifyService
.getService()
.error(err, { title: strings.getDownloadRenderedWorkpadFailureErrorMessage() });
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getDownloadRenderedWorkpadFailureErrorMessage() });
}
};

Expand All @@ -45,9 +48,8 @@ export const downloadRuntime = async (basePath: string) => {
window.open(path);
return;
} catch (err) {
notifyService
.getService()
.error(err, { title: strings.getDownloadRuntimeFailureErrorMessage() });
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getDownloadRuntimeFailureErrorMessage() });
}
};

Expand All @@ -56,8 +58,7 @@ export const downloadZippedRuntime = async (data: any) => {
const zip = new Blob([data], { type: 'octet/stream' });
fileSaver.saveAs(zip, 'canvas-workpad-embed.zip');
} catch (err) {
notifyService
.getService()
.error(err, { title: strings.getDownloadZippedRuntimeFailureErrorMessage() });
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getDownloadZippedRuntimeFailureErrorMessage() });
}
};
28 changes: 16 additions & 12 deletions x-pack/plugins/canvas/public/lib/element_handler_creators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { camelCase } from 'lodash';
import { getClipboardData, setClipboardData } from './clipboard';
import { cloneSubgraphs } from './clone_subgraphs';
import { notifyService } from '../services';
import { useNotifyService } from '../services';
import * as customElementService from './custom_element_service';
import { getId } from './get_id';
import { PositionedElement } from '../../types';
Expand Down Expand Up @@ -70,6 +70,8 @@ export const basicHandlerCreators = {
description = '',
image = ''
): void => {
const notifyService = useNotifyService();

if (selectedNodes.length) {
const content = JSON.stringify({ selectedNodes });
const customElement = {
Expand All @@ -83,17 +85,15 @@ export const basicHandlerCreators = {
customElementService
.create(customElement)
.then(() =>
notifyService
.getService()
.success(
`Custom element '${customElement.displayName || customElement.id}' was saved`,
{
'data-test-subj': 'canvasCustomElementCreate-success',
}
)
notifyService.success(
`Custom element '${customElement.displayName || customElement.id}' was saved`,
{
'data-test-subj': 'canvasCustomElementCreate-success',
}
)
)
.catch((error: Error) =>
notifyService.getService().warning(error, {
notifyService.warning(error, {
title: `Custom element '${
customElement.displayName || customElement.id
}' was not saved`,
Expand Down Expand Up @@ -135,16 +135,20 @@ export const groupHandlerCreators = {
// handlers for cut/copy/paste
export const clipboardHandlerCreators = {
cutNodes: ({ pageId, removeNodes, selectedNodes }: Props) => (): void => {
const notifyService = useNotifyService();

if (selectedNodes.length) {
setClipboardData({ selectedNodes });
removeNodes(selectedNodes.map(extractId), pageId);
notifyService.getService().success('Cut element to clipboard');
notifyService.success('Cut element to clipboard');
}
},
copyNodes: ({ selectedNodes }: Props) => (): void => {
const notifyService = useNotifyService();

if (selectedNodes.length) {
setClipboardData({ selectedNodes });
notifyService.getService().success('Copied element to clipboard');
notifyService.success('Copied element to clipboard');
}
},
pasteNodes: ({ insertNodes, pageId, selectToplevelNodes }: Props) => (): void => {
Expand Down
29 changes: 16 additions & 13 deletions x-pack/plugins/canvas/public/lib/es_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
* 2.0.
*/

// TODO - clint: convert to service abstraction

import { IndexPatternAttributes } from 'src/plugins/data/public';

import { API_ROUTE } from '../../common/lib/constants';
import { fetch } from '../../common/lib/fetch';
import { ErrorStrings } from '../../i18n';
import { notifyService } from '../services';
import { pluginServices } from '../services';
import { platformService } from '../services';

const { esService: strings } = ErrorStrings;
Expand All @@ -36,11 +38,12 @@ export const getFields = (index = '_all') => {
.filter((field) => !field.startsWith('_')) // filters out meta fields
.sort()
)
.catch((err: Error) =>
notifyService.getService().error(err, {
.catch((err: Error) => {
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, {
title: strings.getFieldsFetchErrorMessage(index),
})
);
});
});
};

export const getIndices = () =>
Expand All @@ -56,9 +59,10 @@ export const getIndices = () =>
return savedObject.attributes.title;
});
})
.catch((err: Error) =>
notifyService.getService().error(err, { title: strings.getIndicesFetchErrorMessage() })
);
.catch((err: Error) => {
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getIndicesFetchErrorMessage() });
});

export const getDefaultIndex = () => {
const defaultIndexId = getAdvancedSettings().get('defaultIndex');
Expand All @@ -67,10 +71,9 @@ export const getDefaultIndex = () => {
? getSavedObjectsClient()
.get<IndexPatternAttributes>('index-pattern', defaultIndexId)
.then((defaultIndex) => defaultIndex.attributes.title)
.catch((err) =>
notifyService
.getService()
.error(err, { title: strings.getDefaultIndexFetchErrorMessage() })
)
.catch((err) => {
const notifyService = pluginServices.getServices().notify;
notifyService.error(err, { title: strings.getDefaultIndexFetchErrorMessage() });
})
: Promise.resolve('');
};
5 changes: 3 additions & 2 deletions x-pack/plugins/canvas/public/lib/run_interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { fromExpression, getType } from '@kbn/interpreter/common';
import { ExpressionValue, ExpressionAstExpression } from 'src/plugins/expressions/public';
import { notifyService, expressionsService } from '../services';
import { pluginServices, expressionsService } from '../services';

interface Options {
castToRender?: boolean;
Expand Down Expand Up @@ -57,7 +57,8 @@ export async function runInterpreter(

throw new Error(`Ack! I don't know how to render a '${getType(renderable)}'`);
} catch (err) {
notifyService.getService().error(err);
const { error: displayError } = pluginServices.getServices().notify;
displayError(err);
throw err;
}
}
8 changes: 4 additions & 4 deletions x-pack/plugins/canvas/public/routes/workpad/workpad_route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { ExportApp } from '../../components/export_app';
import { CanvasLoading } from '../../components/canvas_loading';
// @ts-expect-error
import { fetchAllRenderables } from '../../state/actions/elements';
import { useServices } from '../../services';
import { useNotifyService } from '../../services';
import { CanvasWorkpad } from '../../../types';
import { ErrorStrings } from '../../../i18n';
import { useWorkpad } from './hooks/use_workpad';
Expand Down Expand Up @@ -98,13 +98,13 @@ const WorkpadLoaderComponent: FC<{
children: (workpad: CanvasWorkpad) => JSX.Element;
}> = ({ params, children, loadPages }) => {
const [workpad, error] = useWorkpad(params.id, loadPages);
const services = useServices();
const notifyService = useNotifyService();

useEffect(() => {
if (error) {
services.notify.error(error, { title: strings.getLoadFailureErrorMessage() });
notifyService.error(error, { title: strings.getLoadFailureErrorMessage() });
}
}, [error, services.notify]);
}, [error, notifyService]);

if (error) {
return <Redirect to="/" />;
Expand Down
3 changes: 3 additions & 0 deletions x-pack/plugins/canvas/public/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ export * from './legacy';

import { PluginServices } from '../../../../../src/plugins/presentation_util/public';
import { CanvasWorkpadService } from './workpad';
import { CanvasNotifyService } from './notify';

export interface CanvasPluginServices {
workpad: CanvasWorkpadService;
notify: CanvasNotifyService;
}

export const pluginServices = new PluginServices<CanvasPluginServices>();

export const useWorkpadService = () => (() => pluginServices.getHooks().workpad.useService())();
export const useNotifyService = () => (() => pluginServices.getHooks().notify.useService())();
3 changes: 3 additions & 0 deletions x-pack/plugins/canvas/public/services/kibana/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@ import {
} from '../../../../../../src/plugins/presentation_util/public';

import { workpadServiceFactory } from './workpad';
import { notifyServiceFactory } from './notify';
import { CanvasPluginServices } from '..';
import { CanvasStartDeps } from '../../plugin';

export { workpadServiceFactory } from './workpad';
export { notifyServiceFactory } from './notify';

export const pluginServiceProviders: PluginServiceProviders<
CanvasPluginServices,
KibanaPluginServiceParams<CanvasStartDeps>
> = {
workpad: new PluginServiceProvider(workpadServiceFactory),
notify: new PluginServiceProvider(notifyServiceFactory),
};

export const pluginServiceRegistry = new PluginServiceRegistry<
Expand Down
Loading

0 comments on commit e781468

Please sign in to comment.