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

[Dashboard] Keep managed panels out of unmanaged dashboards #176006

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import { showSaveModal } from '@kbn/saved-objects-plugin/public';
import { cloneDeep } from 'lodash';
import React from 'react';
import { batch } from 'react-redux';
import { DashboardContainerInput } from '../../../../common';

import { EmbeddableInput, isReferenceOrValueEmbeddable } from '@kbn/embeddable-plugin/public';
import { DashboardContainerInput, DashboardPanelMap } from '../../../../common';
import { DASHBOARD_CONTENT_ID, SAVED_OBJECT_POST_TIME } from '../../../dashboard_constants';
import {
SaveDashboardReturn,
Expand Down Expand Up @@ -241,12 +243,38 @@ export async function runClone(this: DashboardContainer) {
};
}

const isManaged = this.getState().componentState.managed;
const newPanels = await (async () => {
if (!isManaged) return currentState.panels;

// this is a managed dashboard - unlink all by reference embeddables on clone
const unlinkedPanels: DashboardPanelMap = {};
for (const [panelId, panel] of Object.entries(currentState.panels)) {
const child = this.getChild(panelId);
if (
child &&
isReferenceOrValueEmbeddable(child) &&
child.inputIsRefType(child.getInput() as EmbeddableInput)
) {
const valueTypeInput = await child.getInputAsValueType();
unlinkedPanels[panelId] = {
...panel,
explicitInput: valueTypeInput,
};
continue;
}
unlinkedPanels[panelId] = panel;
}
return unlinkedPanels;
})();

const saveResult = await saveDashboardState({
saveOptions: {
saveAsCopy: true,
},
currentState: {
...stateToSave,
panels: newPanels,
title: newTitle,
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('add panel flyout', () => {
getEmbeddableFactory: embeddableStart.getEmbeddableFactory,
}
);
container.addNewEmbeddable = jest.fn();
container.addNewEmbeddable = jest.fn().mockResolvedValue({ id: 'foo' });
});

test('add panel flyout renders SavedObjectFinder', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
SavedObjectEmbeddableInput,
EmbeddableFactoryNotFoundError,
} from '../lib';
import { savedObjectToPanel } from '../registry/saved_object_to_panel_methods';

type FactoryMap = { [key: string]: EmbeddableFactory };

Expand Down Expand Up @@ -101,12 +102,30 @@ export const AddPanelFlyout = ({
throw new EmbeddableFactoryNotFoundError(type);
}

const embeddable = await container.addNewEmbeddable<SavedObjectEmbeddableInput>(
factoryForSavedObjectType.type,
{ savedObjectId: id },
savedObject.attributes
);
onAddPanel?.(embeddable.id);
let embeddableId: string;

if (savedObjectToPanel[type]) {
// this panel type has a custom method for converting saved objects to panels
const panel = savedObjectToPanel[type](savedObject);

const { id: _embeddableId } = await container.addNewEmbeddable(
factoryForSavedObjectType.type,
panel,
savedObject.attributes
);

embeddableId = _embeddableId;
} else {
const { id: _embeddableId } = await container.addNewEmbeddable<SavedObjectEmbeddableInput>(
factoryForSavedObjectType.type,
{ savedObjectId: id },
savedObject.attributes
);

embeddableId = _embeddableId;
}

onAddPanel?.(embeddableId);

showSuccessToast(name);
runAddTelemetry(container.type, factoryForSavedObjectType, savedObject);
Expand Down Expand Up @@ -136,6 +155,14 @@ export const AddPanelFlyout = ({
noItemsMessage={i18n.translate('embeddableApi.addPanel.noMatchingObjectsMessage', {
defaultMessage: 'No matching objects found.',
})}
getTooltipText={(item) => {
return item.managed
? i18n.translate('embeddableApi.addPanel.managedPanelTooltip', {
defaultMessage:
'This panel is managed by Elastic. It can be added but will be unlinked from the library.',
})
: undefined;
}}
/>
</EuiFlyoutBody>
</>
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/embeddable/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ export {
serializeReactEmbeddableTitles,
} from './react_embeddable_system';

export { registerSavedObjectToPanelMethod } from './registry/saved_object_to_panel_methods';

export function plugin(initializerContext: PluginInitializerContext) {
return new EmbeddablePublicPlugin(initializerContext);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { SavedObjectCommon } from '@kbn/saved-objects-finder-plugin/common';

type SavedObjectToPanelMethod<TSavedObjectAttributes, TByValueInput> = (
savedObject: SavedObjectCommon<TSavedObjectAttributes>
) => { savedObjectId: string } | Partial<TByValueInput>;
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice generics here! Thanks for the suggestion @davismcphee.


export const savedObjectToPanel: Record<string, SavedObjectToPanelMethod<any, any>> = {};

export const registerSavedObjectToPanelMethod = <TSavedObjectAttributes, TByValueAttributes>(
savedObjectType: string,
method: SavedObjectToPanelMethod<TSavedObjectAttributes, TByValueAttributes>
) => {
savedObjectToPanel[savedObjectType] = method;
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@
const nextTick = () => new Promise((res) => process.nextTick(res));

import lodash from 'lodash';
jest.spyOn(lodash, 'debounce').mockImplementation((fn: any) => fn);
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
jest.spyOn(lodash, 'debounce').mockImplementation((fn: any) => {
fn.cancel = jest.fn();
return fn;
});
import {
EuiInMemoryTable,
EuiLink,
Expand Down Expand Up @@ -962,4 +967,36 @@ describe('SavedObjectsFinder', () => {
expect(findTestSubject(wrapper, 'tableHeaderCell_references_2')).toHaveLength(0);
});
});

it('should add a tooltip when text is provided', async () => {
(contentClient.mSearch as any as jest.SpyInstance).mockResolvedValue({
hits: [doc, doc2, doc3],
});

const tooltipText = 'This is a tooltip';

render(
<SavedObjectFinder
services={{ uiSettings, contentClient, savedObjectsTagging }}
savedObjectMetaData={metaDataConfig}
getTooltipText={(item) => (item.id === doc3.id ? tooltipText : undefined)}
/>
);

const assertTooltip = async (linkTitle: string, show: boolean) => {
const elem = await screen.findByText(linkTitle);
userEvent.hover(elem);

const tooltip = screen.queryByText(tooltipText);
if (show) {
expect(tooltip).toBeInTheDocument();
} else {
expect(tooltip).toBeNull();
}
};

assertTooltip(doc.attributes.title, false);
assertTooltip(doc2.attributes.title, false);
assertTooltip(doc3.attributes.title, true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ interface BaseSavedObjectFinder {
leftChildren?: ReactElement | ReactElement[];
children?: ReactElement | ReactElement[];
helpText?: string;
getTooltipText?: (item: SavedObjectFinderItem) => string | undefined;
}

interface SavedObjectFinderFixedPage extends BaseSavedObjectFinder {
Expand Down Expand Up @@ -288,7 +289,7 @@ export class SavedObjectFinderUi extends React.Component<
? currentSavedObjectMetaData.getTooltipForSavedObject(item.simple)
: `${item.name} (${currentSavedObjectMetaData!.name})`;

return (
const link = (
<EuiLink
onClick={
onChoose
Expand All @@ -303,6 +304,16 @@ export class SavedObjectFinderUi extends React.Component<
{item.name}
</EuiLink>
);

const tooltipText = this.props.getTooltipText?.(item);

return tooltipText ? (
<EuiToolTip position="left" content={tooltipText}>
{link}
</EuiToolTip>
) : (
link
);
},
},
...(tagColumn ? [tagColumn] : []),
Expand Down
17 changes: 16 additions & 1 deletion src/plugins/saved_search/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ import type {
ContentManagementPublicStart,
} from '@kbn/content-management-plugin/public';
import type { SOWithMetadata } from '@kbn/content-management-utils';
import type { EmbeddableStart } from '@kbn/embeddable-plugin/public';
import { EmbeddableStart, registerSavedObjectToPanelMethod } from '@kbn/embeddable-plugin/public';
import {
getSavedSearch,
saveSavedSearch,
SaveSavedSearchOptions,
getNewSavedSearch,
SavedSearchUnwrapResult,
SearchByValueInput,
} from './services/saved_searches';
import { SavedSearch, SavedSearchAttributes } from '../common/types';
import { SavedSearchType, LATEST_VERSION } from '../common';
Expand All @@ -35,6 +36,7 @@ import {
getSavedSearchAttributeService,
toSavedSearch,
} from './services/saved_searches';
import { savedObjectToEmbeddableAttributes } from './services/saved_searches/saved_search_attribute_service';

/**
* Saved search plugin public Setup contract
Expand Down Expand Up @@ -115,6 +117,19 @@ export class SavedSearchPublicPlugin

expressions.registerType(kibanaContext);

registerSavedObjectToPanelMethod<SavedSearchAttributes, SearchByValueInput>(
SavedSearchType,
(savedObject) => {
if (!savedObject.managed) {
return { savedObjectId: savedObject.id };
}

return {
attributes: savedObjectToEmbeddableAttributes(savedObject),
};
}
);

return {};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import type { AttributeService, EmbeddableStart } from '@kbn/embeddable-plugin/public';
import type { OnSaveProps } from '@kbn/saved-objects-plugin/public';
import { SEARCH_EMBEDDABLE_TYPE } from '@kbn/discover-utils';
import { SavedObjectCommon } from '@kbn/saved-objects-finder-plugin/common';
import { SavedSearchAttributes } from '../../../common';
import type {
SavedSearch,
SavedSearchByValueAttributes,
Expand Down Expand Up @@ -41,6 +43,13 @@ export type SavedSearchAttributeService = AttributeService<
SavedSearchUnwrapMetaInfo
>;

export const savedObjectToEmbeddableAttributes = (
savedObject: SavedObjectCommon<SavedSearchAttributes>
) => ({
...savedObject.attributes,
references: savedObject.references,
});

export function getSavedSearchAttributeService(
services: SavedSearchesServiceDeps & {
embeddable: EmbeddableStart;
Expand All @@ -67,10 +76,7 @@ export function getSavedSearchAttributeService(
const so = await getSearchSavedObject(savedObjectId, createGetSavedSearchDeps(services));

return {
attributes: {
...so.item.attributes,
references: so.item.references,
},
attributes: savedObjectToEmbeddableAttributes(so.item),
metaInfo: {
sharingSavedObjectProps: so.meta,
managed: so.item.managed,
Expand Down
1 change: 1 addition & 0 deletions src/plugins/saved_search/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@kbn/logging",
"@kbn/core-plugins-server",
"@kbn/utility-types",
"@kbn/saved-objects-finder-plugin",
],
"exclude": [
"target/**/*",
Expand Down
47 changes: 44 additions & 3 deletions src/plugins/visualizations/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ import type { UsageCollectionStart } from '@kbn/usage-collection-plugin/public';
import type { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
import type { ExpressionsSetup, ExpressionsStart } from '@kbn/expressions-plugin/public';
import type { EmbeddableSetup, EmbeddableStart } from '@kbn/embeddable-plugin/public';
import {
EmbeddableSetup,
EmbeddableStart,
registerSavedObjectToPanelMethod,
} from '@kbn/embeddable-plugin/public';
import type { SavedObjectTaggingOssPluginStart } from '@kbn/saved-objects-tagging-oss-plugin/public';
import type { NavigationPublicPluginStart as NavigationStart } from '@kbn/navigation-plugin/public';
import type { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public';
Expand Down Expand Up @@ -112,8 +116,14 @@ import {
} from './services';
import { VisualizeConstants } from '../common/constants';
import { EditInLensAction } from './actions/edit_in_lens_action';
import { ListingViewRegistry } from './types';
import { LATEST_VERSION, CONTENT_ID } from '../common/content_management';
import { ListingViewRegistry, SerializedVis } from './types';
import {
LATEST_VERSION,
CONTENT_ID,
VisualizationSavedObjectAttributes,
} from '../common/content_management';
import { SerializedVisData } from '../common';
import { VisualizeByValueInput } from './embeddable/visualize_embeddable';

/**
* Interface for this plugin's returned setup/start contracts.
Expand Down Expand Up @@ -397,6 +407,37 @@ export class VisualizationsPlugin
name: 'Visualize Library',
});

registerSavedObjectToPanelMethod<VisualizationSavedObjectAttributes, VisualizeByValueInput>(
CONTENT_ID,
(savedObject) => {
const visState = savedObject.attributes.visState;

// not sure if visState actually is ever undefined, but following the type
if (!savedObject.managed || !visState) {
return {
savedObjectId: savedObject.id,
};
}

// data is not always defined, so I added a default value since the extract
// routine in the embeddable factory expects it to be there
const savedVis = JSON.parse(visState) as Omit<SerializedVis, 'data'> & {
data?: SerializedVisData;
};

if (!savedVis.data) {
savedVis.data = {
searchSource: {},
aggs: [],
};
}

return {
savedVis: savedVis as SerializedVis, // now we're sure we have "data" prop
};
}
);

return {
...this.types.setup(),
visEditorsRegistry,
Expand Down
Loading