[Index Management] Add dynamic tabs to the index details page (#169570)

## Summary

Fixes https://github.com/elastic/kibana/issues/168699
This PR adds a new function to the extensions service in Index
Management to register additional tabs into the index details page. I
think we will be adding more content using this service and it might
change the interface of the service later on.

To add a new tab, add Index Management as a dependency to your plugin
and use the `addIndexDetailsTab` function in the extensions service. The
interface for the tab is as follows:
```ts
export interface IndexDetailsTab {
  // a unique key to identify the tab
  id: IndexDetailsTabIds;
  // a text that is displayed on the tab label, usually a Formatted message component
  name: ReactNode;
  // a function that renders the content of the tab
  renderTabContent: (indexName: string, index: Index) => ReactNode;
  // a number to specify the order of the tabs
  order: number;
}
```

### How to test
1. Add a test tab from the ILM plugin using this test commit
74a771db65
2. Start Kibana and ES with `yarn es snapshot` and `yarn start`
3. Navigate to Index Management and click on any index name
4. Verify that the tab is displayed correctly and the tab header is in
the correct order

### 
Screenshot
<img width="1042" alt="Screenshot 2023-10-24 at 15 59 10"
src="7929f5db-8d2a-41d9-9e6d-4d1f74a93a35">


### Screen recording  


6826f68c-c90d-47b1-ae3e-da6e6981d7ba


### Checklist

- [ ] 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
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] 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:
Yulia Čech 2023-10-27 16:05:50 +02:00 committed by GitHub
parent 88db223247
commit 54385c577d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 170 additions and 41 deletions

View file

@ -14,7 +14,7 @@ import {
import { HttpSetup } from '@kbn/core/public';
import { act } from 'react-dom/test-utils';
import { IndexDetailsSection } from '../../../common/constants';
import { IndexDetailsTabIds } from '../../../common/constants';
import { IndexDetailsPage } from '../../../public/application/sections/home/index_list/details_page';
import { WithAppDependencies } from '../helpers';
import { testIndexName } from './mocks';
@ -35,7 +35,8 @@ export interface IndexDetailsPageTestBed extends TestBed {
routerMock: typeof reactRouterMock;
actions: {
getHeader: () => string;
clickIndexDetailsTab: (tab: IndexDetailsSection) => Promise<void>;
clickIndexDetailsTab: (tab: IndexDetailsTabIds) => Promise<void>;
getIndexDetailsTabs: () => string[];
getActiveTabContent: () => string;
mappings: {
getCodeBlockContent: () => string;
@ -119,13 +120,19 @@ export const setup = async ({
return component.find('[data-test-subj="indexDetailsHeader"] h1').text();
};
const clickIndexDetailsTab = async (tab: IndexDetailsSection) => {
const clickIndexDetailsTab = async (tab: IndexDetailsTabIds) => {
await act(async () => {
find(`indexDetailsTab-${tab}`).simulate('click');
});
component.update();
};
const getIndexDetailsTabs = () => {
return component
.find('div[role="tablist"] button[data-test-subj^="indexDetailsTab"]')
.map((tab) => tab.text());
};
const getActiveTabContent = () => {
return find('indexDetailsContent').text();
};
@ -284,6 +291,7 @@ export const setup = async ({
actions: {
getHeader,
clickIndexDetailsTab,
getIndexDetailsTabs,
getActiveTabContent,
mappings,
settings,

View file

@ -10,7 +10,11 @@ import { IndexDetailsPageTestBed, setup } from './index_details_page.helpers';
import { act } from 'react-dom/test-utils';
import React from 'react';
import { IndexDetailsSection } from '../../../common/constants';
import {
IndexDetailsSection,
IndexDetailsTab,
IndexDetailsTabIds,
} from '../../../common/constants';
import { API_BASE_PATH, INTERNAL_API_BASE_PATH } from '../../../common';
import {
breadcrumbService,
@ -703,4 +707,58 @@ describe('<IndexDetailsPage />', () => {
);
});
});
describe('extension service tabs', () => {
const testTabId = 'testTab' as IndexDetailsTabIds;
const testContent = 'Test content';
const additionalTab: IndexDetailsTab = {
id: testTabId,
name: 'Test tab',
renderTabContent: () => {
return <span>{testContent}</span>;
},
order: 1,
};
beforeAll(async () => {
const extensionsServiceMock = {
indexDetailsTabs: [additionalTab],
};
await act(async () => {
testBed = await setup({
httpSetup,
dependencies: {
services: { extensionsService: extensionsServiceMock },
},
});
});
testBed.component.update();
});
it('renders an additional tab', async () => {
await testBed.actions.clickIndexDetailsTab(testTabId);
const content = testBed.actions.getActiveTabContent();
expect(content).toEqual(testContent);
});
it('additional tab is the first in the order', () => {
const tabs = testBed.actions.getIndexDetailsTabs();
expect(tabs).toEqual(['Test tab', 'Overview', 'Mappings', 'Settings', 'Statistics']);
});
it('additional tab is the last in the order', async () => {
const extensionsServiceMock = {
indexDetailsTabs: [{ ...additionalTab, order: 100 }],
};
await act(async () => {
testBed = await setup({
httpSetup,
dependencies: {
services: { extensionsService: extensionsServiceMock },
},
});
});
testBed.component.update();
const tabs = testBed.actions.getIndexDetailsTabs();
expect(tabs).toEqual(['Overview', 'Mappings', 'Settings', 'Statistics', 'Test tab']);
});
});
});

View file

@ -5,6 +5,9 @@
* 2.0.
*/
import { ReactNode } from 'react';
import { Index } from '../types';
export enum Section {
Indices = 'indices',
DataStreams = 'data_streams',
@ -19,3 +22,16 @@ export enum IndexDetailsSection {
Settings = 'settings',
Stats = 'stats',
}
export type IndexDetailsTabIds = IndexDetailsSection | string;
export interface IndexDetailsTab {
// a unique key to identify the tab
id: IndexDetailsTabIds;
// a text that is displayed on the tab label, usually a Formatted message component
name: ReactNode;
// a function that renders the content of the tab
renderTabContent: (indexName: string, index: Index) => ReactNode;
// a number to specify the order of the tabs
order: number;
}

View file

@ -49,3 +49,4 @@ export {
export { MAJOR_VERSION } from './plugin';
export { Section, IndexDetailsSection } from './home_sections';
export type { IndexDetailsTab, IndexDetailsTabIds } from './home_sections';

View file

@ -21,7 +21,12 @@ import {
} from '@elastic/eui';
import { SectionLoading } from '@kbn/es-ui-shared-plugin/public';
import { Section, IndexDetailsSection } from '../../../../../../common/constants';
import {
Section,
IndexDetailsSection,
IndexDetailsTab,
IndexDetailsTabIds,
} from '../../../../../../common/constants';
import { getIndexDetailsLink } from '../../../../services/routing';
import { Index } from '../../../../../../common';
import { INDEX_OPEN } from '../../../../../../common/constants';
@ -36,38 +41,56 @@ import { DetailsPageMappings } from './details_page_mappings';
import { DetailsPageOverview } from './details_page_overview';
import { DetailsPageSettings } from './details_page_settings';
const defaultTabs = [
const defaultTabs: IndexDetailsTab[] = [
{
id: IndexDetailsSection.Overview,
name: (
<FormattedMessage id="xpack.idxMgmt.indexDetails.overviewTitle" defaultMessage="Overview" />
),
renderTabContent: (indexName: string, index: Index) => (
<DetailsPageOverview indexDetails={index} />
),
order: 10,
},
{
id: IndexDetailsSection.Mappings,
name: (
<FormattedMessage id="xpack.idxMgmt.indexDetails.mappingsTitle" defaultMessage="Mappings" />
),
renderTabContent: (indexName: string, index: Index) => (
<DetailsPageMappings indexName={indexName} />
),
order: 20,
},
{
id: IndexDetailsSection.Settings,
name: (
<FormattedMessage id="xpack.idxMgmt.indexDetails.settingsTitle" defaultMessage="Settings" />
),
renderTabContent: (indexName: string, index: Index) => (
<DetailsPageSettings indexName={indexName} isIndexOpen={index.status === INDEX_OPEN} />
),
order: 30,
},
];
const statsTab = {
const statsTab: IndexDetailsTab = {
id: IndexDetailsSection.Stats,
name: <FormattedMessage id="xpack.idxMgmt.indexDetails.statsTitle" defaultMessage="Statistics" />,
renderTabContent: (indexName: string, index: Index) => (
<DetailsPageStats indexName={indexName} isIndexOpen={index.status === INDEX_OPEN} />
),
order: 40,
};
const getSelectedTabContent = ({
tab,
tabs,
indexDetailsSection,
index,
indexName,
}: {
tab: IndexDetailsSection;
tabs: IndexDetailsTab[];
indexDetailsSection: IndexDetailsTabIds;
index?: Index | null;
indexName: string;
}) => {
@ -75,39 +98,50 @@ const getSelectedTabContent = ({
if (!index) {
return null;
}
switch (tab) {
case IndexDetailsSection.Overview:
return <DetailsPageOverview indexDetails={index} />;
case IndexDetailsSection.Mappings:
return <DetailsPageMappings indexName={indexName} />;
case IndexDetailsSection.Settings:
return (
<DetailsPageSettings indexName={indexName} isIndexOpen={index.status === INDEX_OPEN} />
);
case IndexDetailsSection.Stats:
return <DetailsPageStats indexName={indexName} isIndexOpen={index.status === INDEX_OPEN} />;
default:
return <DetailsPageOverview indexDetails={index} />;
}
const selectedTab = tabs.find((tab) => tab.id === indexDetailsSection);
return selectedTab ? (
selectedTab.renderTabContent(indexName, index)
) : (
<DetailsPageOverview indexDetails={index} />
);
};
export const DetailsPage: FunctionComponent<
RouteComponentProps<{ indexName: string; indexDetailsSection: IndexDetailsSection }>
> = ({ location: { search }, history }) => {
const { config } = useAppContext();
const {
config,
services: { extensionsService },
} = useAppContext();
const queryParams = useMemo(() => new URLSearchParams(search), [search]);
const indexName = queryParams.get('indexName') ?? '';
const tab = queryParams.get('tab') ?? IndexDetailsSection.Overview;
const tabs = useMemo(() => {
const sortedTabs = [...defaultTabs];
if (config.enableIndexStats) {
sortedTabs.push(statsTab);
}
sortedTabs.push(...extensionsService.indexDetailsTabs);
sortedTabs.sort((tabA, tabB) => {
return tabA.order - tabB.order;
});
return sortedTabs;
}, [config.enableIndexStats, extensionsService.indexDetailsTabs]);
const tabQueryParam = queryParams.get('tab') ?? IndexDetailsSection.Overview;
let indexDetailsSection = IndexDetailsSection.Overview;
if (Object.values(IndexDetailsSection).includes(tab as IndexDetailsSection)) {
indexDetailsSection = tab as IndexDetailsSection;
if (tabs.map((tab) => tab.id).includes(tabQueryParam as IndexDetailsTabIds)) {
indexDetailsSection = tabQueryParam as IndexDetailsSection;
}
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [index, setIndex] = useState<Index | null>();
const selectedTabContent = useMemo(() => {
return getSelectedTabContent({ tab: indexDetailsSection, index, indexName });
}, [index, indexDetailsSection, indexName]);
return getSelectedTabContent({ tabs, indexDetailsSection, index, indexName });
}, [index, indexDetailsSection, indexName, tabs]);
const fetchIndexDetails = useCallback(async () => {
if (indexName) {
setIsLoading(true);
@ -128,7 +162,7 @@ export const DetailsPage: FunctionComponent<
}, [fetchIndexDetails]);
const onSectionChange = useCallback(
(newSection: IndexDetailsSection) => {
(newSection: IndexDetailsTabIds) => {
return history.push(getIndexDetailsLink(indexName, newSection));
},
[history, indexName]
@ -139,16 +173,14 @@ export const DetailsPage: FunctionComponent<
}, [history]);
const headerTabs = useMemo<EuiPageHeaderProps['tabs']>(() => {
const visibleTabs = config.enableIndexStats ? [...defaultTabs, statsTab] : defaultTabs;
return visibleTabs.map((visibleTab) => ({
onClick: () => onSectionChange(visibleTab.id),
isSelected: visibleTab.id === indexDetailsSection,
key: visibleTab.id,
'data-test-subj': `indexDetailsTab-${visibleTab.id}`,
label: visibleTab.name,
return tabs.map((tab) => ({
onClick: () => onSectionChange(tab.id),
isSelected: tab.id === indexDetailsSection,
key: tab.id,
'data-test-subj': `indexDetailsTab-${tab.id}`,
label: tab.name,
}));
}, [indexDetailsSection, onSectionChange, config]);
}, [tabs, indexDetailsSection, onSectionChange]);
if (!indexName) {
return (

View file

@ -5,7 +5,8 @@
* 2.0.
*/
import { Section, IndexDetailsSection } from '../../../common/constants';
import { Section } from '../../../common/constants';
import type { IndexDetailsTabIds } from '../../../common/constants';
export const getTemplateListLink = () => `/templates`;
@ -57,7 +58,7 @@ export const getDataStreamDetailsLink = (name: string) => {
return encodeURI(`/data_streams/${encodeURIComponent(name)}`);
};
export const getIndexDetailsLink = (indexName: string, tab?: IndexDetailsSection) => {
export const getIndexDetailsLink = (indexName: string, tab?: IndexDetailsTabIds) => {
let link = `/${Section.Indices}/index_details?indexName=${encodeURIComponent(indexName)}`;
if (tab) {
link = `${link}&tab=${tab}`;

View file

@ -17,6 +17,7 @@ const createServiceMock = (): ExtensionsSetupMock => ({
addFilter: jest.fn(),
addSummary: jest.fn(),
addToggle: jest.fn(),
addIndexDetailsTab: jest.fn(),
});
const createMock = () => {

View file

@ -6,6 +6,7 @@
*/
import { i18n } from '@kbn/i18n';
import type { IndexDetailsTab } from '../../common/constants';
export interface ExtensionsSetup {
addSummary(summary: any): void;
@ -14,9 +15,11 @@ export interface ExtensionsSetup {
addFilter(filter: any): void;
addBadge(badge: any): void;
addToggle(toggle: any): void;
addIndexDetailsTab(tab: IndexDetailsTab): void;
}
export class ExtensionsService {
private _indexDetailsTabs: IndexDetailsTab[] = [];
private _summaries: any[] = [];
private _actions: any[] = [];
private _banners: any[] = [];
@ -44,6 +47,7 @@ export class ExtensionsService {
addFilter: this.addFilter.bind(this),
addSummary: this.addSummary.bind(this),
addToggle: this.addToggle.bind(this),
addIndexDetailsTab: this.addIndexDetailsTab.bind(this),
};
return this.service;
@ -73,6 +77,10 @@ export class ExtensionsService {
this._toggles.push(toggle);
}
private addIndexDetailsTab(tab: IndexDetailsTab) {
this._indexDetailsTabs.push(tab);
}
public get summaries() {
return this._summaries;
}
@ -96,4 +104,8 @@ export class ExtensionsService {
public get toggles() {
return this._toggles;
}
public get indexDetailsTabs() {
return this._indexDetailsTabs;
}
}