Skip to content

Commit

Permalink
[Serverless] Sidenav API cleanup (elastic#174544)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga authored Jan 18, 2024
1 parent b3c9bf0 commit 51b8993
Show file tree
Hide file tree
Showing 77 changed files with 2,960 additions and 5,346 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { toArray } from 'rxjs/operators';
import { injectedMetadataServiceMock } from '@kbn/core-injected-metadata-browser-mocks';
import { docLinksServiceMock } from '@kbn/core-doc-links-browser-mocks';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
import { coreContextMock } from '@kbn/core-base-browser-mocks';
import type { App, PublicAppInfo } from '@kbn/core-application-browser';
import { applicationServiceMock } from '@kbn/core-application-browser-mocks';
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
Expand Down Expand Up @@ -75,6 +76,7 @@ function defaultStartTestOptions({
return {
browserSupportsCsp,
kibanaVersion,
coreContext: coreContextMock.create(),
};
}

Expand All @@ -83,7 +85,10 @@ async function start({
cspConfigMock = { warnLegacyBrowsers: true },
startDeps = defaultStartDeps(),
}: { options?: any; cspConfigMock?: any; startDeps?: ReturnType<typeof defaultStartDeps> } = {}) {
const service = new ChromeService(options);
const service = new ChromeService({
...options,
coreContext: options.coreContext ?? coreContextMock.create(),
});

if (cspConfigMock) {
startDeps.injectedMetadata.getCspConfig.mockReturnValue(cspConfigMock);
Expand Down Expand Up @@ -200,22 +205,6 @@ describe('start', () => {
expect(shallow(React.createElement(() => chrome.getHeaderComponent()))).toBeDefined();
});

it('renders the default project side navigation', async () => {
const { chrome } = await start({
startDeps: defaultStartDeps([{ id: 'foo', title: 'Foo' } as App], 'foo'),
});

chrome.setChromeStyle('project');

const component = mount(chrome.getHeaderComponent());

const projectHeader = findTestSubject(component, 'kibanaProjectHeader');
expect(projectHeader.length).toBe(1);

const defaultProjectSideNav = findTestSubject(component, 'defaultProjectSideNav');
expect(defaultProjectSideNav.length).toBe(1);
});

it('renders the custom project side navigation', async () => {
const { chrome } = await start({
startDeps: defaultStartDeps([{ id: 'foo', title: 'Foo' } as App], 'foo'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
* Side Public License, v 1.
*/

import React from 'react';
import React, { useMemo } from 'react';
import { FormattedMessage } from '@kbn/i18n-react';
import { BehaviorSubject, combineLatest, merge, type Observable, of, ReplaySubject } from 'rxjs';
import { mergeMap, map, takeUntil } from 'rxjs/operators';
import { parse } from 'url';
import { EuiLink } from '@elastic/eui';
import useObservable from 'react-use/lib/useObservable';

import type { CoreContext } from '@kbn/core-base-browser-internal';
import type { InternalInjectedMetadataStart } from '@kbn/core-injected-metadata-browser-internal';
import type { AnalyticsServiceSetup } from '@kbn/core-analytics-browser';
import { type DocLinksStart } from '@kbn/core-doc-links-browser';
Expand All @@ -29,21 +31,24 @@ import type {
ChromeHelpExtension,
ChromeUserBanner,
ChromeStyle,
ChromeProjectNavigation,
ChromeSetProjectBreadcrumbsParams,
NavigationTreeDefinition,
AppDeepLinkId,
CloudURLs,
} from '@kbn/core-chrome-browser';
import type { CustomBrandingStart } from '@kbn/core-custom-branding-browser';
import type {
SideNavComponent as ISideNavComponent,
ChromeHelpMenuLink,
} from '@kbn/core-chrome-browser';

import { Logger } from '@kbn/logging';
import { DocTitleService } from './doc_title';
import { NavControlsService } from './nav_controls';
import { NavLinksService } from './nav_links';
import { ProjectNavigationService } from './project_navigation';
import { RecentlyAccessedService } from './recently_accessed';
import { Header, LoadingIndicator, ProjectHeader, ProjectSideNavigation } from './ui';
import { Header, LoadingIndicator, ProjectHeader } from './ui';
import { registerAnalyticsContextProvider } from './register_analytics_context_provider';
import type { InternalChromeStart } from './types';
import { HeaderTopBanner } from './ui/header/header_top_banner';
Expand All @@ -54,6 +59,7 @@ const SNAPSHOT_REGEX = /-snapshot/i;
interface ConstructorParams {
browserSupportsCsp: boolean;
kibanaVersion: string;
coreContext: CoreContext;
}

export interface SetupDeps {
Expand Down Expand Up @@ -81,8 +87,11 @@ export class ChromeService {
private readonly projectNavigation = new ProjectNavigationService();
private mutationObserver: MutationObserver | undefined;
private readonly isSideNavCollapsed$ = new BehaviorSubject<boolean>(true);
private logger: Logger;

constructor(private readonly params: ConstructorParams) {}
constructor(private readonly params: ConstructorParams) {
this.logger = params.coreContext.logger.get('chrome-browser');
}

/**
* These observables allow consumers to toggle the chrome visibility via either:
Expand Down Expand Up @@ -225,9 +234,10 @@ export class ChromeService {
const navLinks = this.navLinks.start({ application, http });
const projectNavigation = this.projectNavigation.start({
application,
navLinks,
navLinksService: navLinks,
http,
chromeBreadcrumbs$: breadcrumbs$,
logger: this.logger,
});
const recentlyAccessed = await this.recentlyAccessed.start({ http });
const docTitle = this.docTitle.start();
Expand Down Expand Up @@ -265,13 +275,20 @@ export class ChromeService {

const setProjectSideNavComponent = (component: ISideNavComponent | null) => {
validateChromeStyle();
projectNavigation.setProjectSideNavComponent(component);
projectNavigation.setSideNavComponent(component);
};

const setProjectNavigation = (config: ChromeProjectNavigation) => {
function initProjectNavigation<
LinkId extends AppDeepLinkId = AppDeepLinkId,
Id extends string = string,
ChildrenId extends string = Id
>(
navigationTree$: Observable<NavigationTreeDefinition<LinkId, Id, ChildrenId>>,
deps: { cloudUrls: CloudURLs }
) {
validateChromeStyle();
projectNavigation.setProjectNavigation(config);
};
projectNavigation.initNavigation(navigationTree$, deps);
}

const setProjectBreadcrumbs = (
breadcrumbs: ChromeBreadcrumb[] | ChromeBreadcrumb,
Expand Down Expand Up @@ -362,20 +379,19 @@ export class ChromeService {
const activeNodes$ = projectNavigation.getActiveNodes$();

const ProjectHeaderWithNavigationComponent = () => {
const CustomSideNavComponent = useObservable(projectNavigationComponent$, undefined);
const CustomSideNavComponent = useObservable(projectNavigationComponent$, {
current: null,
});
const activeNodes = useObservable(activeNodes$, []);

const currentProjectBreadcrumbs$ = projectBreadcrumbs$;

let SideNavComponent: ISideNavComponent = () => null;

if (CustomSideNavComponent !== undefined) {
// We have the state from the Observable
SideNavComponent =
CustomSideNavComponent.current !== null
? CustomSideNavComponent.current
: ProjectSideNavigation;
}
const SideNavComponent = useMemo<ISideNavComponent>(() => {
if (CustomSideNavComponent.current) {
return CustomSideNavComponent.current;
}
return () => null;
}, [CustomSideNavComponent]);

return (
<ProjectHeader
Expand Down Expand Up @@ -526,7 +542,8 @@ export class ChromeService {
setProjectsUrl,
setProjectUrl,
setProjectName,
setNavigation: setProjectNavigation,
initNavigation: initProjectNavigation,
getNavigationTreeUi$: () => projectNavigation.getNavigationTreeUi$(),
setSideNavComponent: setProjectSideNavComponent,
setBreadcrumbs: setProjectBreadcrumbs,
getActiveNavigationNodes$: () => projectNavigation.getActiveNodes$(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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 { i18n } from '@kbn/i18n';
import type { CloudLinks, CloudLink, CloudURLs } from '@kbn/core-chrome-browser';

const stripTrailingForwardSlash = (str: string) => {
return str[str.length - 1] === '/' ? str.substring(0, str.length - 1) : str;
};

const parseCloudURLs = (cloudLinks: CloudLinks): CloudLinks => {
const { userAndRoles, billingAndSub, deployment, performance } = cloudLinks;

// We remove potential trailing forward slash ("/") at the end of the URL
// because it breaks future navigation in Cloud console once we navigate there.
const parseLink = (link?: CloudLink): CloudLink | undefined => {
if (!link) return undefined;
return { ...link, href: stripTrailingForwardSlash(link.href) };
};

return {
...cloudLinks,
userAndRoles: parseLink(userAndRoles),
billingAndSub: parseLink(billingAndSub),
deployment: parseLink(deployment),
performance: parseLink(performance),
};
};

export const getCloudLinks = (cloud: CloudURLs): CloudLinks => {
const { billingUrl, deploymentUrl, performanceUrl, usersAndRolesUrl } = cloud;

const links: CloudLinks = {};

if (usersAndRolesUrl) {
links.userAndRoles = {
title: i18n.translate('core.ui.chrome.sideNavigation.cloudLinks.usersAndRolesLinkText', {
defaultMessage: 'Users and roles',
}),
href: usersAndRolesUrl,
};
}

if (performanceUrl) {
links.performance = {
title: i18n.translate('core.ui.chrome.sideNavigation.cloudLinks.performanceLinkText', {
defaultMessage: 'Performance',
}),
href: performanceUrl,
};
}

if (billingUrl) {
links.billingAndSub = {
title: i18n.translate('core.ui.chrome.sideNavigation.cloudLinks.billingLinkText', {
defaultMessage: 'Billing and subscription',
}),
href: billingUrl,
};
}

if (deploymentUrl) {
links.deployment = {
title: i18n.translate('core.ui.chrome.sideNavigation.cloudLinks.deploymentLinkText', {
defaultMessage: 'Project',
}),
href: deploymentUrl,
};
}

return parseCloudURLs(links);
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { cloneDeep } from 'lodash';

import type { NavigationGroupPreset } from '@kbn/core-chrome-browser';
import {
defaultNavigation as analytics,
type AnalyticsNodeDefinition,
Expand All @@ -22,8 +23,6 @@ import {
type ManagementNodeDefinition,
} from '@kbn/default-nav-management';

import type { NavigationGroupPreset } from './types';

export function getPresets(preset: 'devtools'): DevToolsNodeDefinition;
export function getPresets(preset: 'management'): ManagementNodeDefinition;
export function getPresets(preset: 'ml'): MlNodeDefinition;
Expand Down
Loading

0 comments on commit 51b8993

Please sign in to comment.