Compute dashboard panel selection list lazily (#187797)

## Summary

Closes https://github.com/elastic/kibana/issues/187587

This PR changes how the dashboard panel selection items get computed, it
had previously been computed eagerly, in this implementation panel
selection items would only be computed when the user actually clicks the
`add panel` button, with it's results cached so that subsequent
interactions with the `add panel` button leverages the already computed
data.

**Notable Mention:**
The options presented as the dashboard panel list now only comprise of
uiActions specifically registered with the uiAction trigger
`ADD_PANEL_TRIGGER` and specific dashboard visualisation types. See
https://github.com/elastic/kibana/pull/187797#discussion_r1681320456 to
follow the reasoning behind this.

That been said adding new panels to the dashboard, would be something
along the following lines;


```ts
import { ADD_PANEL_TRIGGER } from '@kbn/ui-actions-plugin/public';

 uiActions.attachAction(ADD_PANEL_TRIGGER, <registredActionId>);

// alternatively
// uiActions.addTriggerAction(ADD_PANEL_TRIGGER, ...someActionDefintion);
````

### Visuals

7c029a64-2cd8-4e3e-af5a-44b6788faa45

### How to test 
- Navigate to a dashboard of choice
- Slow down your network speed using your browser dev tools, refresh
your dashboard, and click on the “Add panel” button as soon as it is
available (before the panels have a chance to load).
- You should be presented with a loading indicator, that eventually is
swapped out for the list of panels available for selection.


### Checklist

Delete any items that are not applicable to this PR.
<!--
- [ ] 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 -->
- [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] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
<!--
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)

### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
-->
This commit is contained in:
Eyo O. Eyo 2024-07-26 13:54:22 +02:00 committed by GitHub
parent b75d74a9fa
commit 6ddffb57fb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 1009 additions and 722 deletions

View file

@ -55,7 +55,7 @@ const onAddPanelActionClick =
export const getAddPanelActionMenuItemsGroup = (
api: PresentationContainer,
actions: Array<Action<object>> | undefined,
closePopover: () => void
onPanelSelected: () => void
) => {
const grouped: Record<string, GroupedAddPanelActions> = {};
@ -72,7 +72,7 @@ export const getAddPanelActionMenuItemsGroup = (
name: actionName,
icon:
(typeof item.getIconType === 'function' ? item.getIconType(context) : undefined) ?? 'empty',
onClick: onAddPanelActionClick(item, context, closePopover),
onClick: onAddPanelActionClick(item, context, onPanelSelected),
'data-test-subj': `create-action-${actionName}`,
description: item?.getDisplayNameTooltip?.(context),
order: item.order ?? 0,

View file

@ -0,0 +1,110 @@
/*
* 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 React, { type ComponentProps } from 'react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import { DashboardPanelSelectionListFlyout } from './dashboard_panel_selection_flyout';
import type { GroupedAddPanelActions } from './add_panel_action_menu_items';
const defaultProps: Omit<
ComponentProps<typeof DashboardPanelSelectionListFlyout>,
'fetchDashboardPanels'
> = {
close: jest.fn(),
paddingSize: 's',
};
const renderComponent = ({
fetchDashboardPanels,
}: Pick<ComponentProps<typeof DashboardPanelSelectionListFlyout>, 'fetchDashboardPanels'>) =>
render(
<IntlProvider locale="en">
<DashboardPanelSelectionListFlyout
{...defaultProps}
fetchDashboardPanels={fetchDashboardPanels}
/>
</IntlProvider>
);
const panelConfiguration: GroupedAddPanelActions[] = [
{
id: 'panel1',
title: 'App 1',
items: [
{
icon: 'icon1',
id: 'mockFactory',
name: 'Factory 1',
description: 'Factory 1 description',
'data-test-subj': 'createNew-mockFactory',
onClick: jest.fn(),
order: 0,
},
],
order: 10,
'data-test-subj': 'dashboardEditorMenu-group1Group',
},
];
describe('DashboardPanelSelectionListFlyout', () => {
it('renders a loading indicator when fetchDashboardPanel has not yielded any value', async () => {
const promiseDelay = 5000;
renderComponent({
fetchDashboardPanels: jest.fn(
() =>
new Promise((resolve) => {
setTimeout(() => resolve(panelConfiguration), promiseDelay);
})
),
});
expect(
await screen.findByTestId('dashboardPanelSelectionLoadingIndicator')
).toBeInTheDocument();
});
it('renders an error indicator when fetchDashboardPanel errors', async () => {
renderComponent({
fetchDashboardPanels: jest.fn().mockRejectedValue(new Error('simulated error')),
});
expect(await screen.findByTestId('dashboardPanelSelectionErrorIndicator')).toBeInTheDocument();
});
it('renders the list of available panels when fetchDashboardPanel resolves a value', async () => {
renderComponent({ fetchDashboardPanels: jest.fn().mockResolvedValue(panelConfiguration) });
expect(await screen.findByTestId(panelConfiguration[0]['data-test-subj']!)).toBeInTheDocument();
});
it('renders a not found message when a user searches for an item that is not in the selection list', async () => {
renderComponent({ fetchDashboardPanels: jest.fn().mockResolvedValue(panelConfiguration) });
expect(await screen.findByTestId(panelConfiguration[0]['data-test-subj']!)).toBeInTheDocument();
act(() => {
userEvent.type(
screen.getByTestId('dashboardPanelSelectionFlyout__searchInput'),
'non existent panel'
);
});
expect(await screen.findByTestId('dashboardPanelSelectionNoPanelMessage')).toBeInTheDocument();
});
it('invokes the close method when the flyout close btn is clicked', async () => {
renderComponent({ fetchDashboardPanels: jest.fn().mockResolvedValue(panelConfiguration) });
fireEvent.click(await screen.findByTestId('dashboardPanelSelectionCloseBtn'));
expect(defaultProps.close).toHaveBeenCalled();
});
});

View file

@ -0,0 +1,287 @@
/*
* 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 React, { useEffect, useState } from 'react';
import { i18n as i18nFn } from '@kbn/i18n';
import { type EuiFlyoutProps, EuiLoadingChart } from '@elastic/eui';
import orderBy from 'lodash/orderBy';
import {
EuiEmptyPrompt,
EuiButtonEmpty,
EuiFlexGroup,
EuiFlexItem,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiFlyoutHeader,
EuiForm,
EuiBadge,
EuiFormRow,
EuiTitle,
EuiFieldSearch,
useEuiTheme,
EuiListGroup,
EuiListGroupItem,
EuiToolTip,
EuiText,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import {
type PanelSelectionMenuItem,
type GroupedAddPanelActions,
} from './add_panel_action_menu_items';
export interface DashboardPanelSelectionListFlyoutProps {
/** Handler to close flyout */
close: () => void;
/** Padding for flyout */
paddingSize: Exclude<EuiFlyoutProps['paddingSize'], 'none' | undefined>;
/** Fetches the panels available for a dashboard */
fetchDashboardPanels: () => Promise<GroupedAddPanelActions[]>;
}
export const DashboardPanelSelectionListFlyout: React.FC<
DashboardPanelSelectionListFlyoutProps
> = ({ close, paddingSize, fetchDashboardPanels }) => {
const { euiTheme } = useEuiTheme();
const [{ data: panels, loading, error }, setPanelState] = useState<{
loading: boolean;
data: GroupedAddPanelActions[] | null;
error: unknown | null;
}>({ loading: true, data: null, error: null });
const [searchTerm, setSearchTerm] = useState<string>('');
const [panelsSearchResult, setPanelsSearchResult] = useState<GroupedAddPanelActions[] | null>(
panels
);
useEffect(() => {
const requestDashboardPanels = () => {
fetchDashboardPanels()
.then((_panels) =>
setPanelState((prevState) => ({
...prevState,
loading: false,
data: _panels,
}))
)
.catch((err) =>
setPanelState((prevState) => ({
...prevState,
loading: false,
error: err,
}))
);
};
requestDashboardPanels();
}, [fetchDashboardPanels]);
useEffect(() => {
const _panels = (panels ?? []).slice(0);
if (!searchTerm) {
return setPanelsSearchResult(_panels);
}
const q = searchTerm.toLowerCase();
setPanelsSearchResult(
orderBy(
_panels.map((panel) => {
const groupSearchMatch = panel.title.toLowerCase().includes(q);
const [groupSearchMatchAgg, items] = panel.items.reduce(
(acc, cur) => {
const searchMatch = cur.name.toLowerCase().includes(q);
acc[0] = acc[0] || searchMatch;
acc[1].push({
...cur,
isDisabled: !(groupSearchMatch || searchMatch),
});
return acc;
},
[groupSearchMatch, [] as PanelSelectionMenuItem[]]
);
return {
...panel,
isDisabled: !groupSearchMatchAgg,
items,
};
}),
['isDisabled']
)
);
}, [panels, searchTerm]);
return (
<>
<EuiFlyoutHeader hasBorder>
<EuiTitle size="m">
<h1 id="addPanelsFlyout">
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.headingText"
defaultMessage="Add panel"
/>
</h1>
</EuiTitle>
</EuiFlyoutHeader>
<EuiFlyoutBody>
<EuiFlexGroup direction="column" responsive={false} gutterSize="m">
<EuiFlexItem
grow={false}
css={{
position: 'sticky',
top: euiTheme.size[paddingSize],
zIndex: 1,
boxShadow: `0 -${euiTheme.size[paddingSize]} 0 4px ${euiTheme.colors.emptyShade}`,
}}
>
<EuiForm component="form" fullWidth>
<EuiFormRow css={{ backgroundColor: euiTheme.colors.emptyShade }}>
<EuiFieldSearch
autoFocus
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
}}
aria-label={i18nFn.translate(
'dashboard.editorMenu.addPanelFlyout.searchLabelText',
{ defaultMessage: 'search field for panels' }
)}
className="nsPanelSelectionFlyout__searchInput"
data-test-subj="dashboardPanelSelectionFlyout__searchInput"
/>
</EuiFormRow>
</EuiForm>
</EuiFlexItem>
<EuiFlexItem
css={{
minHeight: '20vh',
...(loading || error
? {
justifyContent: 'center',
alignItems: 'center',
}
: {}),
}}
>
{loading ? (
<EuiEmptyPrompt
data-test-subj="dashboardPanelSelectionLoadingIndicator"
icon={<EuiLoadingChart size="l" mono />}
/>
) : (
<EuiFlexGroup
direction="column"
gutterSize="m"
data-test-subj="dashboardPanelSelectionList"
>
{panelsSearchResult?.some(({ isDisabled }) => !isDisabled) ? (
panelsSearchResult.map(
({ id, title, items, isDisabled, ['data-test-subj']: dataTestSubj }) =>
!isDisabled ? (
<EuiFlexItem key={id} data-test-subj={dataTestSubj}>
<EuiTitle id={`${id}-group`} size="xxs">
{typeof title === 'string' ? <h3>{title}</h3> : title}
</EuiTitle>
<EuiListGroup
aria-labelledby={`${id}-group`}
size="s"
gutterSize="none"
maxWidth={false}
flush
>
{items?.map((item, idx) => {
return (
<EuiListGroupItem
key={`${id}.${idx}`}
label={
<EuiToolTip position="right" content={item.description}>
{!item.isDeprecated ? (
<EuiText size="s">{item.name}</EuiText>
) : (
<EuiFlexGroup wrap responsive={false} gutterSize="s">
<EuiFlexItem grow={false}>
<EuiText size="s">{item.name}</EuiText>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiBadge color="warning">
<FormattedMessage
id="dashboard.editorMenu.deprecatedTag"
defaultMessage="Deprecated"
/>
</EuiBadge>
</EuiFlexItem>
</EuiFlexGroup>
)}
</EuiToolTip>
}
onClick={item?.onClick}
iconType={item.icon}
data-test-subj={item['data-test-subj']}
isDisabled={item.isDisabled}
/>
);
})}
</EuiListGroup>
</EuiFlexItem>
) : null
)
) : (
<>
{Boolean(error) ? (
<EuiEmptyPrompt
iconType="warning"
iconColor="danger"
body={
<EuiText size="s" textAlign="center">
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.loadingErrorDescription"
defaultMessage="An error occurred loading the available dashboard panels for selection"
/>
</EuiText>
}
data-test-subj="dashboardPanelSelectionErrorIndicator"
/>
) : (
<EuiText
size="s"
textAlign="center"
data-test-subj="dashboardPanelSelectionNoPanelMessage"
>
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.noResultsDescription"
defaultMessage="No panel types found"
/>
</EuiText>
)}
</>
)}
</EuiFlexGroup>
)}
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="spaceBetween">
<EuiFlexItem grow={false}>
<EuiButtonEmpty onClick={close} data-test-subj="dashboardPanelSelectionCloseBtn">
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.cancelButtonText"
defaultMessage="Close"
/>
</EuiButtonEmpty>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</>
);
};

View file

@ -0,0 +1,10 @@
/*
* 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.
*/
export { useGetDashboardPanels } from './use_get_dashboard_panels';
export { DashboardPanelSelectionListFlyout } from './dashboard_panel_selection_flyout';

View file

@ -0,0 +1,220 @@
/*
* 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 { renderHook } from '@testing-library/react-hooks';
import { ADD_PANEL_TRIGGER } from '@kbn/ui-actions-plugin/public';
import type { PresentationContainer } from '@kbn/presentation-containers';
import type { Action } from '@kbn/ui-actions-plugin/public';
import { type BaseVisType, VisGroups, VisTypeAlias } from '@kbn/visualizations-plugin/public';
import { COMMON_EMBEDDABLE_GROUPING } from '@kbn/embeddable-plugin/public';
import { useGetDashboardPanels } from './use_get_dashboard_panels';
import { pluginServices } from '../../../services/plugin_services';
const mockApi = { addNewPanel: jest.fn() } as unknown as jest.Mocked<PresentationContainer>;
describe('Get dashboard panels hook', () => {
const defaultHookProps: Parameters<typeof useGetDashboardPanels>[0] = {
api: mockApi,
createNewVisType: jest.fn(),
};
type PluginServices = ReturnType<typeof pluginServices.getServices>;
let compatibleTriggerActionsRequestSpy: jest.SpyInstance<
ReturnType<NonNullable<PluginServices['uiActions']['getTriggerCompatibleActions']>>
>;
let dashboardVisualizationGroupGetterSpy: jest.SpyInstance<
ReturnType<PluginServices['visualizations']['getByGroup']>
>;
let dashboardVisualizationAliasesGetterSpy: jest.SpyInstance<
ReturnType<PluginServices['visualizations']['getAliases']>
>;
beforeAll(() => {
const _pluginServices = pluginServices.getServices();
compatibleTriggerActionsRequestSpy = jest.spyOn(
_pluginServices.uiActions,
'getTriggerCompatibleActions'
);
dashboardVisualizationGroupGetterSpy = jest.spyOn(_pluginServices.visualizations, 'getByGroup');
dashboardVisualizationAliasesGetterSpy = jest.spyOn(
_pluginServices.visualizations,
'getAliases'
);
});
beforeEach(() => {
compatibleTriggerActionsRequestSpy.mockResolvedValue([]);
dashboardVisualizationGroupGetterSpy.mockReturnValue([]);
dashboardVisualizationAliasesGetterSpy.mockReturnValue([]);
});
afterEach(() => {
jest.clearAllMocks();
});
afterAll(() => {
jest.resetAllMocks();
});
describe('useGetDashboardPanels', () => {
it('hook return value is callable', () => {
const { result } = renderHook(() => useGetDashboardPanels(defaultHookProps));
expect(result.current).toBeInstanceOf(Function);
});
it('returns a callable method that yields a cached result if invoked after a prior resolution', async () => {
const { result } = renderHook(() => useGetDashboardPanels(defaultHookProps));
expect(result.current).toBeInstanceOf(Function);
const firstInvocationResult = await result.current(jest.fn());
expect(compatibleTriggerActionsRequestSpy).toHaveBeenCalledWith(ADD_PANEL_TRIGGER, {
embeddable: expect.objectContaining(mockApi),
});
const secondInvocationResult = await result.current(jest.fn());
expect(firstInvocationResult).toStrictEqual(secondInvocationResult);
expect(compatibleTriggerActionsRequestSpy).toHaveBeenCalledTimes(1);
});
});
describe('augmenting ui action group items with dashboard visualization types', () => {
it.each([
['visualizations', VisGroups.PROMOTED],
[COMMON_EMBEDDABLE_GROUPING.legacy.id, VisGroups.LEGACY],
[COMMON_EMBEDDABLE_GROUPING.annotation.id, VisGroups.TOOLS],
])(
'includes in the ui action %s group, %s dashboard visualization group types',
async (uiActionGroupId, dashboardVisualizationGroupId) => {
const mockVisualizationsUiAction: Action<object> = {
id: `some-${uiActionGroupId}-action`,
type: '',
order: 10,
grouping: [
{
id: uiActionGroupId,
order: 1000,
getDisplayName: jest.fn(),
getIconType: jest.fn(),
},
],
getDisplayName: jest.fn(() => `Some ${uiActionGroupId} visualization Action`),
getIconType: jest.fn(),
execute: jest.fn(),
isCompatible: jest.fn(() => Promise.resolve(true)),
};
const mockDashboardVisualizationType = {
name: dashboardVisualizationGroupId,
title: dashboardVisualizationGroupId,
order: 0,
description: `This is a dummy representation of a ${dashboardVisualizationGroupId} visualization.`,
icon: 'empty',
stage: 'production',
isDeprecated: false,
group: dashboardVisualizationGroupId,
titleInWizard: `Custom ${dashboardVisualizationGroupId} visualization`,
} as BaseVisType;
compatibleTriggerActionsRequestSpy.mockResolvedValue([mockVisualizationsUiAction]);
dashboardVisualizationGroupGetterSpy.mockImplementation((group) => {
if (group !== dashboardVisualizationGroupId) return [];
return [mockDashboardVisualizationType];
});
const { result } = renderHook(() => useGetDashboardPanels(defaultHookProps));
expect(result.current).toBeInstanceOf(Function);
expect(await result.current(jest.fn())).toStrictEqual(
expect.arrayContaining([
expect.objectContaining({
id: uiActionGroupId,
'data-test-subj': `dashboardEditorMenu-${uiActionGroupId}Group`,
items: expect.arrayContaining([
expect.objectContaining({
// @ts-expect-error ignore passing the required context in this test
'data-test-subj': `create-action-${mockVisualizationsUiAction.getDisplayName()}`,
}),
expect.objectContaining({
'data-test-subj': `visType-${mockDashboardVisualizationType.name}`,
}),
]),
}),
])
);
}
);
it('includes in the ui action visualization group dashboard visualization alias types', async () => {
const mockVisualizationsUiAction: Action<object> = {
id: 'some-vis-action',
type: '',
order: 10,
grouping: [
{
id: 'visualizations',
order: 1000,
getDisplayName: jest.fn(),
getIconType: jest.fn(),
},
],
getDisplayName: jest.fn(() => 'Some visualization Action'),
getIconType: jest.fn(),
execute: jest.fn(),
isCompatible: jest.fn(() => Promise.resolve(true)),
};
const mockedAliasVisualizationType: VisTypeAlias = {
name: 'alias visualization',
title: 'Alias Visualization',
order: 0,
description: 'This is a dummy representation of aan aliased visualization.',
icon: 'empty',
stage: 'production',
isDeprecated: false,
};
compatibleTriggerActionsRequestSpy.mockResolvedValue([mockVisualizationsUiAction]);
dashboardVisualizationAliasesGetterSpy.mockReturnValue([mockedAliasVisualizationType]);
const { result } = renderHook(() => useGetDashboardPanels(defaultHookProps));
expect(result.current).toBeInstanceOf(Function);
expect(await result.current(jest.fn())).toStrictEqual(
expect.arrayContaining([
expect.objectContaining({
id: mockVisualizationsUiAction.grouping![0].id,
'data-test-subj': `dashboardEditorMenu-${
mockVisualizationsUiAction.grouping![0].id
}Group`,
items: expect.arrayContaining([
expect.objectContaining({
// @ts-expect-error ignore passing the required context in this test
'data-test-subj': `create-action-${mockVisualizationsUiAction.getDisplayName()}`,
}),
expect.objectContaining({
'data-test-subj': `visType-${mockedAliasVisualizationType.name}`,
}),
]),
}),
])
);
});
});
});

View file

@ -0,0 +1,220 @@
/*
* 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 { useMemo, useRef, useCallback } from 'react';
import type { IconType } from '@elastic/eui';
import { ADD_PANEL_TRIGGER } from '@kbn/ui-actions-plugin/public';
import { type Subscription, AsyncSubject, from, defer, map, lastValueFrom } from 'rxjs';
import { EmbeddableFactory, COMMON_EMBEDDABLE_GROUPING } from '@kbn/embeddable-plugin/public';
import { PresentationContainer } from '@kbn/presentation-containers';
import { type BaseVisType, VisGroups, type VisTypeAlias } from '@kbn/visualizations-plugin/public';
import { pluginServices } from '../../../services/plugin_services';
import {
getAddPanelActionMenuItemsGroup,
type PanelSelectionMenuItem,
type GroupedAddPanelActions,
} from './add_panel_action_menu_items';
interface UseGetDashboardPanelsArgs {
api: PresentationContainer;
createNewVisType: (visType: BaseVisType | VisTypeAlias) => () => void;
}
export interface FactoryGroup {
id: string;
appName: string;
icon?: IconType;
factories: EmbeddableFactory[];
order: number;
}
const sortGroupPanelsByOrder = <T extends { order: number }>(panelGroups: T[]): T[] => {
return panelGroups.sort(
// larger number sorted to the top
(panelGroupA, panelGroupB) => panelGroupB.order - panelGroupA.order
);
};
export const useGetDashboardPanels = ({ api, createNewVisType }: UseGetDashboardPanelsArgs) => {
const panelsComputeResultCache = useRef(new AsyncSubject<GroupedAddPanelActions[]>());
const panelsComputeSubscription = useRef<Subscription | null>(null);
const {
uiActions,
visualizations: { getAliases: getVisTypeAliases, getByGroup: getVisTypesByGroup },
} = pluginServices.getServices();
const getSortedVisTypesByGroup = (group: VisGroups) =>
getVisTypesByGroup(group)
.sort((a: BaseVisType | VisTypeAlias, b: BaseVisType | VisTypeAlias) => {
const labelA = 'titleInWizard' in a ? a.titleInWizard || a.title : a.title;
const labelB = 'titleInWizard' in b ? b.titleInWizard || a.title : a.title;
if (labelA < labelB) {
return -1;
}
if (labelA > labelB) {
return 1;
}
return 0;
})
.filter(({ disableCreate }: BaseVisType) => !disableCreate);
const promotedVisTypes = getSortedVisTypesByGroup(VisGroups.PROMOTED);
const toolVisTypes = getSortedVisTypesByGroup(VisGroups.TOOLS);
const legacyVisTypes = getSortedVisTypesByGroup(VisGroups.LEGACY);
const visTypeAliases = getVisTypeAliases()
.sort(({ promotion: a = false }: VisTypeAlias, { promotion: b = false }: VisTypeAlias) =>
a === b ? 0 : a ? -1 : 1
)
.filter(({ disableCreate }: VisTypeAlias) => !disableCreate);
const augmentedCreateNewVisType = useCallback(
(visType: Parameters<typeof createNewVisType>[0], cb: () => void) => {
const visClickHandler = createNewVisType(visType);
return () => {
visClickHandler();
cb();
};
},
[createNewVisType]
);
const getVisTypeMenuItem = useCallback(
(onClickCb: () => void, visType: BaseVisType): PanelSelectionMenuItem => {
const {
name,
title,
titleInWizard,
description,
icon = 'empty',
isDeprecated,
order,
} = visType;
return {
id: name,
name: titleInWizard || title,
isDeprecated,
icon,
onClick: augmentedCreateNewVisType(visType, onClickCb),
'data-test-subj': `visType-${name}`,
description,
order,
};
},
[augmentedCreateNewVisType]
);
const getVisTypeAliasMenuItem = useCallback(
(onClickCb: () => void, visTypeAlias: VisTypeAlias): PanelSelectionMenuItem => {
const { name, title, description, icon = 'empty', order } = visTypeAlias;
return {
id: name,
name: title,
icon,
onClick: augmentedCreateNewVisType(visTypeAlias, onClickCb),
'data-test-subj': `visType-${name}`,
description,
order: order ?? 0,
};
},
[augmentedCreateNewVisType]
);
const addPanelAction$ = useMemo(
() =>
defer(() => {
return from(
uiActions?.getTriggerCompatibleActions?.(ADD_PANEL_TRIGGER, {
embeddable: api,
}) ?? []
);
}),
[api, uiActions]
);
const computeAvailablePanels = useCallback(
(onPanelSelected: () => void) => {
if (!panelsComputeSubscription.current) {
panelsComputeSubscription.current = addPanelAction$
.pipe(
map((addPanelActions) =>
getAddPanelActionMenuItemsGroup(api, addPanelActions, onPanelSelected)
),
map((groupedAddPanelAction) => {
return sortGroupPanelsByOrder<GroupedAddPanelActions>(
Object.values(groupedAddPanelAction)
).map((panelGroup) => {
switch (panelGroup.id) {
case 'visualizations': {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
// TODO: actually add grouping to vis type alias so we wouldn't randomly display an unintended item
visTypeAliases.map(getVisTypeAliasMenuItem.bind(null, onPanelSelected)),
promotedVisTypes.map(getVisTypeMenuItem.bind(null, onPanelSelected))
)
),
};
}
case COMMON_EMBEDDABLE_GROUPING.legacy.id: {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
legacyVisTypes.map(getVisTypeMenuItem.bind(null, onPanelSelected))
)
),
};
}
case COMMON_EMBEDDABLE_GROUPING.annotation.id: {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
toolVisTypes.map(getVisTypeMenuItem.bind(null, onPanelSelected))
)
),
};
}
default: {
return {
...panelGroup,
items: sortGroupPanelsByOrder(panelGroup.items),
};
}
}
});
})
)
.subscribe(panelsComputeResultCache.current);
}
},
[
api,
addPanelAction$,
getVisTypeMenuItem,
getVisTypeAliasMenuItem,
toolVisTypes,
legacyVisTypes,
promotedVisTypes,
visTypeAliases,
]
);
return useCallback(
(...args: Parameters<typeof computeAvailablePanels>) => {
computeAvailablePanels(...args);
return lastValueFrom(panelsComputeResultCache.current.asObservable());
},
[computeAvailablePanels]
);
};

View file

@ -6,134 +6,53 @@
* Side Public License, v 1.
*/
import { EmbeddableFactory } from '@kbn/embeddable-plugin/public';
import React, { ComponentProps } from 'react';
import { render } from '@testing-library/react';
import { PresentationContainer } from '@kbn/presentation-containers';
import { GroupedAddPanelActions } from './add_panel_action_menu_items';
import {
FactoryGroup,
mergeGroupedItemsProvider,
getEmbeddableFactoryMenuItemProvider,
} from './editor_menu';
import { EditorMenu } from './editor_menu';
import { DashboardAPIContext } from '../dashboard_app';
import { buildMockDashboard } from '../../mocks';
describe('mergeGroupedItemsProvider', () => {
const mockApi = { addNewPanel: jest.fn() } as unknown as jest.Mocked<PresentationContainer>;
const closePopoverSpy = jest.fn();
import { pluginServices } from '../../services/plugin_services';
const getEmbeddableFactoryMenuItem = getEmbeddableFactoryMenuItemProvider(
mockApi,
closePopoverSpy
);
jest.mock('../../services/plugin_services', () => {
const module = jest.requireActual('../../services/plugin_services');
const mockFactory = {
id: 'factory1',
type: 'mockFactory',
getDisplayName: () => 'Factory 1',
getDescription: () => 'Factory 1 description',
getIconType: () => 'icon1',
} as unknown as EmbeddableFactory;
const _pluginServices = (module.pluginServices as typeof pluginServices).getServices();
const factoryGroupMap = {
group1: {
id: 'panel1',
appName: 'App 1',
icon: 'icon1',
order: 10,
factories: [mockFactory],
jest
.spyOn(_pluginServices.embeddable, 'getEmbeddableFactories')
.mockReturnValue(new Map().values());
jest.spyOn(_pluginServices.uiActions, 'getTriggerCompatibleActions').mockResolvedValue([]);
jest.spyOn(_pluginServices.visualizations, 'getByGroup').mockReturnValue([]);
jest.spyOn(_pluginServices.visualizations, 'getAliases').mockReturnValue([]);
return {
...module,
pluginServices: {
...module.pluginServices,
getServices: jest.fn().mockReturnValue(_pluginServices),
},
} as unknown as Record<string, FactoryGroup>;
};
});
const groupedAddPanelAction = {
group1: {
id: 'panel2',
title: 'Panel 2',
icon: 'icon2',
order: 10,
items: [
{
id: 'addPanelActionId',
order: 0,
},
],
},
} as unknown as Record<string, GroupedAddPanelActions>;
const mockApi = { addNewPanel: jest.fn() } as unknown as jest.Mocked<PresentationContainer>;
it('should merge factoryGroupMap and groupedAddPanelAction correctly', () => {
const groupedPanels = mergeGroupedItemsProvider(getEmbeddableFactoryMenuItem)(
factoryGroupMap,
groupedAddPanelAction
);
describe('editor menu', () => {
const defaultProps: ComponentProps<typeof EditorMenu> = {
api: mockApi,
createNewVisType: jest.fn(),
};
expect(groupedPanels).toEqual([
{
id: 'panel1',
title: 'App 1',
items: [
{
icon: 'icon1',
name: 'Factory 1',
id: 'mockFactory',
description: 'Factory 1 description',
'data-test-subj': 'createNew-mockFactory',
onClick: expect.any(Function),
order: 0,
},
{
id: 'addPanelActionId',
order: 0,
},
],
'data-test-subj': 'dashboardEditorMenu-group1Group',
order: 10,
it('renders without crashing', async () => {
render(<EditorMenu {...defaultProps} />, {
wrapper: ({ children }) => {
return (
<DashboardAPIContext.Provider value={buildMockDashboard()}>
{children}
</DashboardAPIContext.Provider>
);
},
]);
});
it('should handle missing factoryGroup correctly', () => {
const groupedPanels = mergeGroupedItemsProvider(getEmbeddableFactoryMenuItem)(
{},
groupedAddPanelAction
);
expect(groupedPanels).toEqual([
{
id: 'panel2',
icon: 'icon2',
title: 'Panel 2',
items: [
{
id: 'addPanelActionId',
order: 0,
},
],
order: 10,
},
]);
});
it('should handle missing groupedAddPanelAction correctly', () => {
const groupedPanels = mergeGroupedItemsProvider(getEmbeddableFactoryMenuItem)(
factoryGroupMap,
{}
);
expect(groupedPanels).toEqual([
{
id: 'panel1',
title: 'App 1',
items: [
{
icon: 'icon1',
id: 'mockFactory',
name: 'Factory 1',
description: 'Factory 1 description',
'data-test-subj': 'createNew-mockFactory',
onClick: expect.any(Function),
order: 0,
},
],
order: 10,
'data-test-subj': 'dashboardEditorMenu-group1Group',
},
]);
});
});
});

View file

@ -8,354 +8,79 @@
import './editor_menu.scss';
import React, { useEffect, useMemo, useState, useRef } from 'react';
import { type IconType } from '@elastic/eui';
import React, { useEffect, useCallback, type ComponentProps } from 'react';
import { i18n } from '@kbn/i18n';
import { type Action, ADD_PANEL_TRIGGER } from '@kbn/ui-actions-plugin/public';
import { toMountPoint } from '@kbn/react-kibana-mount';
import { ToolbarButton } from '@kbn/shared-ux-button-toolbar';
import { PresentationContainer } from '@kbn/presentation-containers';
import { type BaseVisType, VisGroups, type VisTypeAlias } from '@kbn/visualizations-plugin/public';
import { EmbeddableFactory, COMMON_EMBEDDABLE_GROUPING } from '@kbn/embeddable-plugin/public';
import { useGetDashboardPanels, DashboardPanelSelectionListFlyout } from './add_new_panel';
import { pluginServices } from '../../services/plugin_services';
import {
getAddPanelActionMenuItemsGroup,
type PanelSelectionMenuItem,
type GroupedAddPanelActions,
} from './add_panel_action_menu_items';
import { openDashboardPanelSelectionFlyout } from './open_dashboard_panel_selection_flyout';
import type { DashboardServices } from '../../services/types';
import { useDashboardAPI } from '../dashboard_app';
export interface FactoryGroup {
id: string;
appName: string;
icon?: IconType;
factories: EmbeddableFactory[];
order: number;
}
interface UnwrappedEmbeddableFactory {
factory: EmbeddableFactory;
isEditable: boolean;
}
export type GetEmbeddableFactoryMenuItem = ReturnType<typeof getEmbeddableFactoryMenuItemProvider>;
export const getEmbeddableFactoryMenuItemProvider =
(api: PresentationContainer, closePopover: () => void) =>
(factory: EmbeddableFactory): PanelSelectionMenuItem => {
const icon = factory?.getIconType ? factory.getIconType() : 'empty';
return {
id: factory.type,
name: factory.getDisplayName(),
icon,
description: factory.getDescription?.(),
onClick: async () => {
closePopover();
api.addNewPanel({ panelType: factory.type }, true);
},
'data-test-subj': `createNew-${factory.type}`,
order: factory.order ?? 0,
};
};
const sortGroupPanelsByOrder = <T extends { order: number }>(panelGroups: T[]): T[] => {
return panelGroups.sort(
// larger number sorted to the top
(panelGroupA, panelGroupB) => panelGroupB.order - panelGroupA.order
);
};
export const mergeGroupedItemsProvider =
(getEmbeddableFactoryMenuItem: GetEmbeddableFactoryMenuItem) =>
(
factoryGroupMap: Record<string, FactoryGroup>,
groupedAddPanelAction: Record<string, GroupedAddPanelActions>
) => {
const panelGroups: GroupedAddPanelActions[] = [];
new Set(Object.keys(factoryGroupMap).concat(Object.keys(groupedAddPanelAction))).forEach(
(groupId) => {
const dataTestSubj = `dashboardEditorMenu-${groupId}Group`;
const factoryGroup = factoryGroupMap[groupId];
const addPanelGroup = groupedAddPanelAction[groupId];
if (factoryGroup && addPanelGroup) {
panelGroups.push({
id: factoryGroup.id,
title: factoryGroup.appName,
'data-test-subj': dataTestSubj,
order: factoryGroup.order,
items: [
...factoryGroup.factories.map(getEmbeddableFactoryMenuItem),
...(addPanelGroup?.items ?? []),
],
});
} else if (factoryGroup) {
panelGroups.push({
id: factoryGroup.id,
title: factoryGroup.appName,
'data-test-subj': dataTestSubj,
order: factoryGroup.order,
items: factoryGroup.factories.map(getEmbeddableFactoryMenuItem),
});
} else if (addPanelGroup) {
panelGroups.push(addPanelGroup);
}
}
);
return panelGroups;
};
interface EditorMenuProps {
api: PresentationContainer;
interface EditorMenuProps
extends Pick<Parameters<typeof useGetDashboardPanels>[0], 'api' | 'createNewVisType'> {
isDisabled?: boolean;
/** Handler for creating new visualization of a specified type */
createNewVisType: (visType: BaseVisType | VisTypeAlias) => () => void;
}
export const EditorMenu = ({ createNewVisType, isDisabled, api }: EditorMenuProps) => {
const isMounted = useRef(false);
const flyoutRef = useRef<ReturnType<DashboardServices['overlays']['openFlyout']>>();
const dashboard = useDashboardAPI();
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
flyoutRef.current?.close();
};
}, []);
const dashboardAPI = useDashboardAPI();
const {
embeddable,
visualizations: { getAliases: getVisTypeAliases, getByGroup: getVisTypesByGroup },
uiActions,
overlays,
analytics,
settings: { i18n: i18nStart, theme },
} = pluginServices.getServices();
const [unwrappedEmbeddableFactories, setUnwrappedEmbeddableFactories] = useState<
UnwrappedEmbeddableFactory[]
>([]);
const [addPanelActions, setAddPanelActions] = useState<Array<Action<object>> | undefined>(
undefined
);
const embeddableFactories = useMemo(
() => Array.from(embeddable.getEmbeddableFactories()),
[embeddable]
);
useEffect(() => {
Promise.all(
embeddableFactories.map<Promise<UnwrappedEmbeddableFactory>>(async (factory) => ({
factory,
isEditable: await factory.isEditable(),
}))
).then((factories) => {
setUnwrappedEmbeddableFactories(factories);
});
}, [embeddableFactories]);
const getSortedVisTypesByGroup = (group: VisGroups) =>
getVisTypesByGroup(group)
.sort((a: BaseVisType | VisTypeAlias, b: BaseVisType | VisTypeAlias) => {
const labelA = 'titleInWizard' in a ? a.titleInWizard || a.title : a.title;
const labelB = 'titleInWizard' in b ? b.titleInWizard || a.title : a.title;
if (labelA < labelB) {
return -1;
}
if (labelA > labelB) {
return 1;
}
return 0;
})
.filter(({ disableCreate }: BaseVisType) => !disableCreate);
const promotedVisTypes = getSortedVisTypesByGroup(VisGroups.PROMOTED);
const toolVisTypes = getSortedVisTypesByGroup(VisGroups.TOOLS);
const legacyVisTypes = getSortedVisTypesByGroup(VisGroups.LEGACY);
const visTypeAliases = getVisTypeAliases()
.sort(({ promotion: a = false }: VisTypeAlias, { promotion: b = false }: VisTypeAlias) =>
a === b ? 0 : a ? -1 : 1
)
.filter(({ disableCreate }: VisTypeAlias) => !disableCreate);
const factories = unwrappedEmbeddableFactories.filter(
({ isEditable, factory: { type, canCreateNew, isContainerType } }) =>
isEditable && !isContainerType && canCreateNew() && type !== 'visualization'
);
const factoryGroupMap: Record<string, FactoryGroup> = {};
// Retrieve ADD_PANEL_TRIGGER actions
useEffect(() => {
async function loadPanelActions() {
const registeredActions = await uiActions?.getTriggerCompatibleActions?.(ADD_PANEL_TRIGGER, {
embeddable: api,
});
if (isMounted.current) {
setAddPanelActions(registeredActions);
}
}
loadPanelActions();
}, [uiActions, api]);
factories.forEach(({ factory }) => {
const { grouping } = factory;
if (grouping) {
grouping.forEach((group) => {
if (factoryGroupMap[group.id]) {
factoryGroupMap[group.id].factories.push(factory);
} else {
factoryGroupMap[group.id] = {
id: group.id,
appName: group.getDisplayName
? group.getDisplayName({ embeddable: dashboard })
: group.id,
icon: group.getIconType?.({ embeddable: dashboard }),
factories: [factory],
order: group.order ?? 0,
};
}
});
} else {
const fallbackGroup = COMMON_EMBEDDABLE_GROUPING.other;
if (!factoryGroupMap[fallbackGroup.id]) {
factoryGroupMap[fallbackGroup.id] = {
id: fallbackGroup.id,
appName: fallbackGroup.getDisplayName
? fallbackGroup.getDisplayName({ embeddable: dashboard })
: fallbackGroup.id,
icon: fallbackGroup.getIconType?.({ embeddable: dashboard }) || 'empty',
factories: [],
order: fallbackGroup.order ?? 0,
};
}
factoryGroupMap[fallbackGroup.id].factories.push(factory);
}
const fetchDashboardPanels = useGetDashboardPanels({
api,
createNewVisType,
});
const augmentedCreateNewVisType = (
visType: Parameters<EditorMenuProps['createNewVisType']>[0],
cb: () => void
) => {
const visClickHandler = createNewVisType(visType);
useEffect(() => {
// ensure opened dashboard is closed if a navigation event happens;
return () => {
visClickHandler();
cb();
dashboardAPI.clearOverlays();
};
};
}, [dashboardAPI]);
const getVisTypeMenuItem = (
onClickCb: () => void,
visType: BaseVisType
): PanelSelectionMenuItem => {
const {
name,
title,
titleInWizard,
description,
icon = 'empty',
isDeprecated,
order,
} = visType;
return {
id: name,
name: titleInWizard || title,
isDeprecated,
icon,
onClick: augmentedCreateNewVisType(visType, onClickCb),
'data-test-subj': `visType-${name}`,
description,
order,
};
};
const openDashboardPanelSelectionFlyout = useCallback(
function openDashboardPanelSelectionFlyout() {
const flyoutPanelPaddingSize: ComponentProps<
typeof DashboardPanelSelectionListFlyout
>['paddingSize'] = 'l';
const getVisTypeAliasMenuItem = (
onClickCb: () => void,
visTypeAlias: VisTypeAlias
): PanelSelectionMenuItem => {
const { name, title, description, icon = 'empty', order } = visTypeAlias;
const mount = toMountPoint(
React.createElement(function () {
return (
<DashboardPanelSelectionListFlyout
close={dashboardAPI.clearOverlays}
{...{
paddingSize: flyoutPanelPaddingSize,
fetchDashboardPanels: fetchDashboardPanels.bind(null, dashboardAPI.clearOverlays),
}}
/>
);
}),
{ analytics, theme, i18n: i18nStart }
);
return {
id: name,
name: title,
icon,
onClick: augmentedCreateNewVisType(visTypeAlias, onClickCb),
'data-test-subj': `visType-${name}`,
description,
order: order ?? 0,
};
};
const getEditorMenuPanels = (closeFlyout: () => void): GroupedAddPanelActions[] => {
const getEmbeddableFactoryMenuItem = getEmbeddableFactoryMenuItemProvider(api, closeFlyout);
const groupedAddPanelAction = getAddPanelActionMenuItemsGroup(
api,
addPanelActions,
closeFlyout
);
const initialPanelGroups = mergeGroupedItemsProvider(getEmbeddableFactoryMenuItem)(
factoryGroupMap,
groupedAddPanelAction
);
// enhance panel groups
return sortGroupPanelsByOrder<GroupedAddPanelActions>(initialPanelGroups).map((panelGroup) => {
switch (panelGroup.id) {
case 'visualizations': {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
// TODO: actually add grouping to vis type alias so we wouldn't randomly display an unintended item
visTypeAliases.map(getVisTypeAliasMenuItem.bind(null, closeFlyout)),
promotedVisTypes.map(getVisTypeMenuItem.bind(null, closeFlyout))
)
),
};
}
case COMMON_EMBEDDABLE_GROUPING.legacy.id: {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
legacyVisTypes.map(getVisTypeMenuItem.bind(null, closeFlyout))
)
),
};
}
case COMMON_EMBEDDABLE_GROUPING.annotation.id: {
return {
...panelGroup,
items: sortGroupPanelsByOrder<PanelSelectionMenuItem>(
(panelGroup.items ?? []).concat(
toolVisTypes.map(getVisTypeMenuItem.bind(null, closeFlyout))
)
),
};
}
default: {
return {
...panelGroup,
items: sortGroupPanelsByOrder(panelGroup.items),
};
}
}
});
};
dashboardAPI.openOverlay(
overlays.openFlyout(mount, {
size: 'm',
maxWidth: 500,
paddingSize: flyoutPanelPaddingSize,
'aria-labelledby': 'addPanelsFlyout',
'data-test-subj': 'dashboardPanelSelectionFlyout',
onClose(overlayRef) {
dashboardAPI.clearOverlays();
overlayRef.close();
},
})
);
},
[analytics, theme, i18nStart, dashboardAPI, overlays, fetchDashboardPanels]
);
return (
<ToolbarButton
@ -365,11 +90,7 @@ export const EditorMenu = ({ createNewVisType, isDisabled, api }: EditorMenuProp
label={i18n.translate('dashboard.solutionToolbar.editorMenuButtonLabel', {
defaultMessage: 'Add panel',
})}
onClick={() => {
flyoutRef.current = openDashboardPanelSelectionFlyout({
getPanels: getEditorMenuPanels,
});
}}
onClick={openDashboardPanelSelectionFlyout}
size="s"
/>
);

View file

@ -1,255 +0,0 @@
/*
* 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 React, { useEffect, useState, useRef } from 'react';
import { toMountPoint } from '@kbn/react-kibana-mount';
import { i18n as i18nFn } from '@kbn/i18n';
import orderBy from 'lodash/orderBy';
import {
EuiButtonEmpty,
EuiFlexGroup,
EuiFlexItem,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiFlyoutHeader,
EuiForm,
EuiBadge,
EuiFormRow,
EuiTitle,
EuiFieldSearch,
useEuiTheme,
type EuiFlyoutProps,
EuiListGroup,
EuiListGroupItem,
EuiToolTip,
EuiText,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { pluginServices } from '../../services/plugin_services';
import type { DashboardServices } from '../../services/types';
import type { GroupedAddPanelActions, PanelSelectionMenuItem } from './add_panel_action_menu_items';
interface OpenDashboardPanelSelectionFlyoutArgs {
getPanels: (closePopover: () => void) => GroupedAddPanelActions[];
flyoutPanelPaddingSize?: Exclude<EuiFlyoutProps['paddingSize'], 'none'>;
}
interface Props extends Pick<OpenDashboardPanelSelectionFlyoutArgs, 'getPanels'> {
/** Handler to close flyout */
close: () => void;
/** Padding for flyout */
paddingSize: Exclude<OpenDashboardPanelSelectionFlyoutArgs['flyoutPanelPaddingSize'], undefined>;
}
export function openDashboardPanelSelectionFlyout({
getPanels,
flyoutPanelPaddingSize = 'l',
}: OpenDashboardPanelSelectionFlyoutArgs) {
const {
overlays,
analytics,
settings: { i18n, theme },
} = pluginServices.getServices();
// eslint-disable-next-line prefer-const
let flyoutRef: ReturnType<DashboardServices['overlays']['openFlyout']>;
const mount = toMountPoint(
React.createElement(function () {
const closeFlyout = () => flyoutRef.close();
return (
<DashboardPanelSelectionListFlyout
close={closeFlyout}
{...{ paddingSize: flyoutPanelPaddingSize, getPanels }}
/>
);
}),
{ analytics, theme, i18n }
);
flyoutRef = overlays.openFlyout(mount, {
size: 'm',
maxWidth: 500,
paddingSize: flyoutPanelPaddingSize,
'aria-labelledby': 'addPanelsFlyout',
'data-test-subj': 'dashboardPanelSelectionFlyout',
});
return flyoutRef;
}
export const DashboardPanelSelectionListFlyout: React.FC<Props> = ({
close,
getPanels,
paddingSize,
}) => {
const { euiTheme } = useEuiTheme();
const panels = useRef(getPanels(close));
const [searchTerm, setSearchTerm] = useState<string>('');
const [panelsSearchResult, setPanelsSearchResult] = useState<GroupedAddPanelActions[]>(
panels.current
);
useEffect(() => {
if (!searchTerm) {
return setPanelsSearchResult(panels.current);
}
const q = searchTerm.toLowerCase();
setPanelsSearchResult(
orderBy(
panels.current.map((panel) => {
const groupSearchMatch = panel.title.toLowerCase().includes(q);
const [groupSearchMatchAgg, items] = panel.items.reduce(
(acc, cur) => {
const searchMatch = cur.name.toLowerCase().includes(q);
acc[0] = acc[0] || searchMatch;
acc[1].push({
...cur,
isDisabled: !(groupSearchMatch || searchMatch),
});
return acc;
},
[groupSearchMatch, [] as PanelSelectionMenuItem[]]
);
return {
...panel,
isDisabled: !groupSearchMatchAgg,
items,
};
}),
['isDisabled']
)
);
}, [searchTerm]);
return (
<>
<EuiFlyoutHeader hasBorder>
<EuiTitle size="m">
<h1 id="addPanelsFlyout">
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.headingText"
defaultMessage="Add panel"
/>
</h1>
</EuiTitle>
</EuiFlyoutHeader>
<EuiFlyoutBody>
<EuiFlexGroup direction="column" responsive={false} gutterSize="m">
<EuiFlexItem
grow={false}
css={{
position: 'sticky',
top: euiTheme.size[paddingSize],
zIndex: 1,
boxShadow: `0 -${euiTheme.size[paddingSize]} 0 4px ${euiTheme.colors.emptyShade}`,
}}
>
<EuiForm component="form" fullWidth>
<EuiFormRow css={{ backgroundColor: euiTheme.colors.emptyShade }}>
<EuiFieldSearch
autoFocus
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
}}
aria-label={i18nFn.translate(
'dashboard.editorMenu.addPanelFlyout.searchLabelText',
{ defaultMessage: 'search field for panels' }
)}
className="nsPanelSelectionFlyout__searchInput"
data-test-subj="dashboardPanelSelectionFlyout__searchInput"
/>
</EuiFormRow>
</EuiForm>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiFlexGroup direction="column" gutterSize="m">
{panelsSearchResult.some(({ isDisabled }) => !isDisabled) ? (
panelsSearchResult.map(
({ id, title, items, isDisabled, ['data-test-subj']: dataTestSubj }) =>
!isDisabled ? (
<EuiFlexItem key={id} data-test-subj={dataTestSubj}>
<EuiTitle id={`${id}-group`} size="xxs">
{typeof title === 'string' ? <h3>{title}</h3> : title}
</EuiTitle>
<EuiListGroup
aria-labelledby={`${id}-group`}
size="s"
gutterSize="none"
maxWidth={false}
flush
>
{items?.map((item, idx) => {
return (
<EuiListGroupItem
key={`${id}.${idx}`}
label={
<EuiToolTip position="right" content={item.description}>
{!item.isDeprecated ? (
<EuiText size="s">{item.name}</EuiText>
) : (
<EuiFlexGroup wrap responsive={false} gutterSize="s">
<EuiFlexItem grow={false}>
<EuiText size="s">{item.name}</EuiText>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiBadge color="warning">
<FormattedMessage
id="dashboard.editorMenu.deprecatedTag"
defaultMessage="Deprecated"
/>
</EuiBadge>
</EuiFlexItem>
</EuiFlexGroup>
)}
</EuiToolTip>
}
onClick={item?.onClick}
iconType={item.icon}
data-test-subj={item['data-test-subj']}
isDisabled={item.isDisabled}
/>
);
})}
</EuiListGroup>
</EuiFlexItem>
) : null
)
) : (
<EuiText size="s" textAlign="center">
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.noResultsDescription"
defaultMessage="No panel types found"
/>
</EuiText>
)}
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="spaceBetween">
<EuiFlexItem grow={false}>
<EuiButtonEmpty onClick={close}>
<FormattedMessage
id="dashboard.solutionToolbar.addPanelFlyout.cancelButtonText"
defaultMessage="Close"
/>
</EuiButtonEmpty>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</>
);
};

View file

@ -53,6 +53,9 @@ export class DashboardAddPanelService extends FtrService {
this.log.debug('DashboardAddPanel.clickEditorMenuButton');
await this.testSubjects.click('dashboardEditorMenuButton');
await this.testSubjects.existOrFail('dashboardPanelSelectionFlyout');
await this.retry.try(async () => {
return await this.testSubjects.exists('dashboardPanelSelectionList');
});
}
async expectEditorMenuClosed() {

View file

@ -648,7 +648,13 @@ export class LensPlugin {
);
// Displays the add ESQL panel in the dashboard add Panel menu
const createESQLPanelAction = new CreateESQLPanelAction(startDependencies, core);
const createESQLPanelAction = new CreateESQLPanelAction(startDependencies, core, async () => {
if (!this.editorFrameService) {
await this.initDependenciesForApi();
}
return this.editorFrameService!;
});
startDependencies.uiActions.addTriggerAction(ADD_PANEL_TRIGGER, createESQLPanelAction);
const discoverLocator = startDependencies.share?.url.locators.get('DISCOVER_APP_LOCATOR');

View file

@ -6,9 +6,10 @@
*/
import type { CoreStart } from '@kbn/core/public';
import { coreMock } from '@kbn/core/public/mocks';
import type { LensPluginStartDependencies } from '../../plugin';
import { createMockStartDependencies } from '../../editor_frame_service/mocks';
import { getMockPresentationContainer } from '@kbn/presentation-containers/mocks';
import type { LensPluginStartDependencies } from '../../plugin';
import type { EditorFrameService } from '../../editor_frame_service';
import { createMockStartDependencies } from '../../editor_frame_service/mocks';
import { CreateESQLPanelAction } from './create_action';
describe('create Lens panel action', () => {
@ -16,9 +17,22 @@ describe('create Lens panel action', () => {
const mockStartDependencies =
createMockStartDependencies() as unknown as LensPluginStartDependencies;
const mockPresentationContainer = getMockPresentationContainer();
const mockEditorFrameService = {
loadVisualizations: jest.fn(),
loadDatasources: jest.fn(),
} as unknown as EditorFrameService;
const mockGetEditorFrameService = jest.fn(() => Promise.resolve(mockEditorFrameService));
describe('compatibility check', () => {
it('is incompatible if ui setting for ES|QL is off', async () => {
const configurablePanelAction = new CreateESQLPanelAction(mockStartDependencies, core);
const configurablePanelAction = new CreateESQLPanelAction(
mockStartDependencies,
core,
mockGetEditorFrameService
);
const isCompatible = await configurablePanelAction.isCompatible({
embeddable: mockPresentationContainer,
});
@ -36,7 +50,13 @@ describe('create Lens panel action', () => {
},
},
} as CoreStart;
const createESQLAction = new CreateESQLPanelAction(mockStartDependencies, updatedCore);
const createESQLAction = new CreateESQLPanelAction(
mockStartDependencies,
updatedCore,
mockGetEditorFrameService
);
const isCompatible = await createESQLAction.isCompatible({
embeddable: mockPresentationContainer,
});

View file

@ -11,6 +11,7 @@ import { EmbeddableApiContext } from '@kbn/presentation-publishing';
import { apiIsPresentationContainer } from '@kbn/presentation-containers';
import { COMMON_VISUALIZATION_GROUPING } from '@kbn/visualizations-plugin/public';
import type { LensPluginStartDependencies } from '../../plugin';
import type { EditorFrameService } from '../../editor_frame_service';
const ACTION_CREATE_ESQL_CHART = 'ACTION_CREATE_ESQL_CHART';
@ -25,7 +26,8 @@ export class CreateESQLPanelAction implements Action<EmbeddableApiContext> {
constructor(
protected readonly startDependencies: LensPluginStartDependencies,
protected readonly core: CoreStart
protected readonly core: CoreStart,
protected readonly getEditorFrameService: () => Promise<EditorFrameService>
) {}
public getDisplayName(): string {
@ -41,18 +43,21 @@ export class CreateESQLPanelAction implements Action<EmbeddableApiContext> {
public async isCompatible({ embeddable }: EmbeddableApiContext) {
if (!apiIsPresentationContainer(embeddable)) return false;
// compatible only when ES|QL advanced setting is enabled
const { isCreateActionCompatible } = await getAsyncHelpers();
return isCreateActionCompatible(this.core);
}
public async execute({ embeddable }: EmbeddableApiContext) {
if (!apiIsPresentationContainer(embeddable)) throw new IncompatibleActionError();
const { executeCreateAction } = await getAsyncHelpers();
const editorFrameService = await this.getEditorFrameService();
executeCreateAction({
deps: this.startDependencies,
core: this.core,
api: embeddable,
editorFrameService,
});
}
}

View file

@ -21,6 +21,7 @@ import { suggestionsApi } from '../../lens_suggestions_api';
import { generateId } from '../../id_generator';
import { executeEditAction } from './edit_action_helpers';
import { Embeddable } from '../../embeddable';
import type { EditorFrameService } from '../../editor_frame_service';
// datasourceMap and visualizationMap setters/getters
export const [getVisualizationMap, setVisualizationMap] = createGetterSetter<
@ -31,7 +32,7 @@ export const [getDatasourceMap, setDatasourceMap] = createGetterSetter<
Record<string, Datasource<unknown, unknown>>
>('DatasourceMap', false);
export function isCreateActionCompatible(core: CoreStart) {
export async function isCreateActionCompatible(core: CoreStart) {
return core.uiSettings.get(ENABLE_ESQL);
}
@ -39,13 +40,13 @@ export async function executeCreateAction({
deps,
core,
api,
editorFrameService,
}: {
deps: LensPluginStartDependencies;
core: CoreStart;
api: PresentationContainer;
editorFrameService: EditorFrameService;
}) {
const isCompatibleAction = isCreateActionCompatible(core);
const getFallbackDataView = async () => {
const indexName = await getIndexForESQLQuery({ dataViews: deps.dataViews });
if (!indexName) return null;
@ -53,13 +54,33 @@ export async function executeCreateAction({
return dataView;
};
const dataView = await getFallbackDataView();
const [isCompatibleAction, dataView] = await Promise.all([
isCreateActionCompatible(core),
getFallbackDataView(),
]);
if (!isCompatibleAction || !dataView) {
throw new IncompatibleActionError();
}
const visualizationMap = getVisualizationMap();
const datasourceMap = getDatasourceMap();
let visualizationMap = getVisualizationMap();
let datasourceMap = getDatasourceMap();
if (!visualizationMap || !datasourceMap) {
[visualizationMap, datasourceMap] = await Promise.all([
editorFrameService.loadVisualizations(),
editorFrameService.loadDatasources(),
]);
if (!visualizationMap && !datasourceMap) {
throw new IncompatibleActionError();
}
// persist for retrieval elsewhere
setDatasourceMap(datasourceMap);
setVisualizationMap(visualizationMap);
}
const defaultIndex = dataView.getIndexPattern();
const defaultEsqlQuery = {