Skip to content

Commit

Permalink
[Dashboard] Keep managed panels out of unmanaged dashboards (elastic#…
Browse files Browse the repository at this point in the history
…176006)

## Summary

Close elastic#172383
Close elastic#172384

This PR introduces a [new embeddable-related
registry](https://github.com/elastic/kibana/pull/176006/files#diff-1401b355377c76ab6458756aa0e3177beef5ec56796c58b7a52b5e003f85b5cf)
which clients can use to define a custom transformation from saved
object to embeddable input during the add-panel-from-library sequence.

Then, each content type uses this to communicate whether a particular
object should be added by-ref or by-val based on the presence of
`managed: true` on the saved object
([example](https://github.com/elastic/kibana/pull/176006/files#diff-3baaeaeef5893a5a4db6379a1ed888406a8584cb9d0c7440f273040e4aa28166R157-R167)).



### Managed panels are added by-value to dashboards

<img width="400" alt="Screenshot 2024-02-01 at 12 24 06 PM"
src="https://github.com/elastic/kibana/assets/315764/42a695d4-fccf-45bf-bd6a-8d8fc606d04e">

### Cloning a managed dashboard inlines all by-ref panels


https://github.com/elastic/kibana/assets/315764/ca6e763c-cc02-46cb-9164-abd91deca081

### Checklist

Delete any items that are not applicable to this PR.

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials — will
happen in elastic#175150
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed —
https://buildkite.com/elastic/kibana-flaky-test-suite-runner/builds/5031
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
2 people authored and CoenWarmer committed Feb 15, 2024
1 parent f6aaa49 commit 259930e
Show file tree
Hide file tree
Showing 20 changed files with 412 additions and 102 deletions.
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>;

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

0 comments on commit 259930e

Please sign in to comment.