Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a workspace dropdown menu in left navigation bar #282

Merged
merged 3 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/core/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export {
StringValidationRegex,
StringValidationRegexString,
WorkspaceObject,
WorkspaceAttribute,
} from '../types';

export {
Expand Down
1 change: 1 addition & 0 deletions src/core/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ function createCoreSetupMock({
} = {}) {
const mock = {
application: applicationServiceMock.createSetupContract(),
chrome: chromeServiceMock.createSetupContract(),
context: contextServiceMock.createSetupContract(),
docLinks: docLinksServiceMock.createSetupContract(),
fatalErrors: fatalErrorsServiceMock.createSetupContract(),
Expand Down
41 changes: 24 additions & 17 deletions src/core/public/workspace/workspaces_service.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,31 @@ import type { PublicMethodsOf } from '@osd/utility-types';
import { WorkspacesService } from './workspaces_service';
import { WorkspaceObject } from '..';

const currentWorkspaceId$ = new BehaviorSubject<string>('');
const workspaceList$ = new BehaviorSubject<WorkspaceObject[]>([]);
const currentWorkspace$ = new BehaviorSubject<WorkspaceObject | null>(null);
const initialized$ = new BehaviorSubject<boolean>(false);

const createWorkspacesSetupContractMock = () => ({
currentWorkspaceId$,
workspaceList$,
currentWorkspace$,
initialized$,
});
const createWorkspacesSetupContractMock = () => {
const currentWorkspaceId$ = new BehaviorSubject<string>('');
const workspaceList$ = new BehaviorSubject<WorkspaceObject[]>([]);
const currentWorkspace$ = new BehaviorSubject<WorkspaceObject | null>(null);
const initialized$ = new BehaviorSubject<boolean>(false);
return {
currentWorkspaceId$,
workspaceList$,
currentWorkspace$,
initialized$,
};
};

const createWorkspacesStartContractMock = () => ({
currentWorkspaceId$,
workspaceList$,
currentWorkspace$,
initialized$,
});
const createWorkspacesStartContractMock = () => {
const currentWorkspaceId$ = new BehaviorSubject<string>('');
const workspaceList$ = new BehaviorSubject<WorkspaceObject[]>([]);
const currentWorkspace$ = new BehaviorSubject<WorkspaceObject | null>(null);
const initialized$ = new BehaviorSubject<boolean>(false);
return {
currentWorkspaceId$,
workspaceList$,
currentWorkspace$,
initialized$,
};
};

export type WorkspacesServiceContract = PublicMethodsOf<WorkspacesService>;
const createMock = (): jest.Mocked<WorkspacesServiceContract> => ({
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/workspace/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/

export const WORKSPACE_CREATE_APP_ID = 'workspace_create';
export const WORKSPACE_LIST_APP_ID = 'workspace_list';
export const WORKSPACE_UPDATE_APP_ID = 'workspace_update';
export const WORKSPACE_OVERVIEW_APP_ID = 'workspace_overview';
export const WORKSPACE_FATAL_ERROR_APP_ID = 'workspace_fatal_error';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';

import { WorkspaceMenu } from './workspace_menu';
import { coreMock } from '../../../../../core/public/mocks';
import { CoreStart } from '../../../../../core/public';

describe('<WorkspaceMenu />', () => {
let coreStartMock: CoreStart;

beforeEach(() => {
coreStartMock = coreMock.createStart();
coreStartMock.workspaces.initialized$.next(true);
jest.spyOn(coreStartMock.application, 'getUrlForApp').mockImplementation((appId: string) => {
return `https://test.com/app/${appId}`;
});
});

afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});

it('should display a list of workspaces in the dropdown', () => {
coreStartMock.workspaces.workspaceList$.next([
{ id: 'workspace-1', name: 'workspace 1' },
{ id: 'workspace-2', name: 'workspace 2' },
]);

render(<WorkspaceMenu coreStart={coreStartMock} />);
fireEvent.click(screen.getByText(/select a workspace/i));

expect(screen.getByText(/workspace 1/i)).toBeInTheDocument();
expect(screen.getByText(/workspace 2/i)).toBeInTheDocument();
});

it('should display current workspace name', () => {
coreStartMock.workspaces.currentWorkspace$.next({ id: 'workspace-1', name: 'workspace 1' });
render(<WorkspaceMenu coreStart={coreStartMock} />);
expect(screen.getByText(/workspace 1/i)).toBeInTheDocument();
});

it('should close the workspace dropdown list', async () => {
render(<WorkspaceMenu coreStart={coreStartMock} />);
fireEvent.click(screen.getByText(/select a workspace/i));

expect(screen.getByLabelText(/close workspace dropdown/i)).toBeInTheDocument();
fireEvent.click(screen.getByLabelText(/close workspace dropdown/i));
await waitFor(() => {
expect(screen.queryByLabelText(/close workspace dropdown/i)).not.toBeInTheDocument();
});
});

it('should navigate to the workspace', () => {
coreStartMock.workspaces.workspaceList$.next([
{ id: 'workspace-1', name: 'workspace 1' },
{ id: 'workspace-2', name: 'workspace 2' },
]);

const originalLocation = window.location;
Object.defineProperty(window, 'location', {
value: {
assign: jest.fn(),
},
});

render(<WorkspaceMenu coreStart={coreStartMock} />);
fireEvent.click(screen.getByText(/select a workspace/i));
fireEvent.click(screen.getByText(/workspace 1/i));

expect(window.location.assign).toHaveBeenCalledWith(
'https://test.com/w/workspace-1/app/workspace_overview'
);

Object.defineProperty(window, 'location', {
value: originalLocation,
});
});

it('should navigate to create workspace page', () => {
const originalLocation = window.location;
Object.defineProperty(window, 'location', {
value: {
assign: jest.fn(),
},
});

render(<WorkspaceMenu coreStart={coreStartMock} />);
fireEvent.click(screen.getByText(/select a workspace/i));
fireEvent.click(screen.getByText(/create workspace/i));
expect(window.location.assign).toHaveBeenCalledWith('https://test.com/app/workspace_create');

Object.defineProperty(window, 'location', {
value: originalLocation,
});
});

it('should navigate to workspace list page', () => {
const originalLocation = window.location;
Object.defineProperty(window, 'location', {
value: {
assign: jest.fn(),
},
});

render(<WorkspaceMenu coreStart={coreStartMock} />);
fireEvent.click(screen.getByText(/select a workspace/i));
fireEvent.click(screen.getByText(/all workspace/i));
expect(window.location.assign).toHaveBeenCalledWith('https://test.com/app/workspace_list');

Object.defineProperty(window, 'location', {
value: originalLocation,
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { i18n } from '@osd/i18n';
import React, { useState } from 'react';
import { useObservable } from 'react-use';
import {
EuiButtonIcon,
EuiContextMenu,
EuiFlexGroup,
EuiFlexItem,
EuiIcon,
EuiListGroup,
EuiListGroupItem,
EuiPopover,
EuiText,
} from '@elastic/eui';
import type { EuiContextMenuPanelItemDescriptor } from '@elastic/eui';

import { WorkspaceAttribute } from '../../../../../core/public';
import {
WORKSPACE_CREATE_APP_ID,
WORKSPACE_LIST_APP_ID,
WORKSPACE_OVERVIEW_APP_ID,
} from '../../../common/constants';
import { formatUrlWithWorkspaceId } from '../../../../../core/public/utils';
import { CoreStart } from '../../../../../core/public';

interface Props {
coreStart: CoreStart;
}

function getFilteredWorkspaceList(
workspaceList: WorkspaceAttribute[],
currentWorkspace: WorkspaceAttribute | null
): WorkspaceAttribute[] {
// list top5 workspaces except management workspace, place current workspace at the top
ruanyl marked this conversation as resolved.
Show resolved Hide resolved
return [
...(currentWorkspace ? [currentWorkspace] : []),
...workspaceList.filter((workspace) => workspace.id !== currentWorkspace?.id),
].slice(0, 5);
}

export const WorkspaceMenu = ({ coreStart }: Props) => {
const [isPopoverOpen, setPopover] = useState(false);
const currentWorkspace = useObservable(coreStart.workspaces.currentWorkspace$, null);
const workspaceList = useObservable(coreStart.workspaces.workspaceList$, []);

const defaultHeaderName = i18n.translate(
'core.ui.primaryNav.workspacePickerMenu.defaultHeaderName',
{
defaultMessage: 'Select a workspace',
}
);
const filteredWorkspaceList = getFilteredWorkspaceList(workspaceList, currentWorkspace);
const currentWorkspaceName = currentWorkspace?.name ?? defaultHeaderName;

const onButtonClick = () => {
setPopover(!isPopoverOpen);
};

const closePopover = () => {
setPopover(false);
};

const workspaceToItem = (workspace: WorkspaceAttribute, index: number) => {
const workspaceURL = formatUrlWithWorkspaceId(
coreStart.application.getUrlForApp(WORKSPACE_OVERVIEW_APP_ID, {
absolute: false,
}),
workspace.id,
coreStart.http.basePath
);
const name =
currentWorkspace !== null && index === 0 ? (
<EuiText>
<strong>{workspace.name}</strong>
</EuiText>
) : (
workspace.name
);
return {
name,
key: index.toString(),
ruanyl marked this conversation as resolved.
Show resolved Hide resolved
icon: <EuiIcon type="stopFilled" color={workspace.color ?? 'primary'} />,
onClick: () => {
window.location.assign(workspaceURL);
},
};
};

const getWorkspaceListItems = () => {
const workspaceListItems: EuiContextMenuPanelItemDescriptor[] = filteredWorkspaceList.map(
(workspace, index) => workspaceToItem(workspace, index)
);
const length = workspaceListItems.length;
workspaceListItems.push({
icon: <EuiIcon type="plus" />,
name: i18n.translate('core.ui.primaryNav.workspaceContextMenu.createWorkspace', {
defaultMessage: 'Create workspace',
}),
key: length.toString(),
ruanyl marked this conversation as resolved.
Show resolved Hide resolved
onClick: () => {
window.location.assign(
coreStart.application.getUrlForApp(WORKSPACE_CREATE_APP_ID, {
absolute: false,
})
);
},
});
workspaceListItems.push({
icon: <EuiIcon type="folderClosed" />,
name: i18n.translate('core.ui.primaryNav.workspaceContextMenu.allWorkspace', {
defaultMessage: 'All workspaces',
}),
key: (length + 1).toString(),
ruanyl marked this conversation as resolved.
Show resolved Hide resolved
onClick: () => {
window.location.assign(
coreStart.application.getUrlForApp(WORKSPACE_LIST_APP_ID, {
absolute: false,
})
);
},
});
return workspaceListItems;
};

const currentWorkspaceButton = (
<>
<EuiListGroup style={{ width: 318 }} maxWidth={false}>
<EuiListGroupItem
iconType="spacesApp"
label={currentWorkspaceName}
onClick={onButtonClick}
extraAction={{
color: 'subdued',
onClick: onButtonClick,
iconType: isPopoverOpen ? 'arrowDown' : 'arrowRight',
iconSize: 's',
'aria-label': 'Show workspace dropdown selector',
alwaysShow: true,
}}
/>
</EuiListGroup>
</>
);

const currentWorkspaceTitle = (
<EuiFlexGroup alignItems="center">
<EuiFlexItem grow={true}>
<EuiText size="s">{currentWorkspaceName}</EuiText>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButtonIcon
iconType="cross"
onClick={closePopover}
aria-label="close workspace dropdown"
/>
</EuiFlexItem>
</EuiFlexGroup>
);

const panels = [
{
id: 0,
title: currentWorkspaceTitle,
items: getWorkspaceListItems(),
},
];

return (
<EuiPopover
id="contextMenuExample"
button={currentWorkspaceButton}
isOpen={isPopoverOpen}
closePopover={closePopover}
panelPaddingSize="none"
anchorPosition="downCenter"
>
<EuiContextMenu initialPanelId={0} panels={panels} />
</EuiPopover>
);
};
7 changes: 7 additions & 0 deletions src/plugins/workspace/public/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,11 @@ describe('Workspace plugin', () => {
coreStart.workspaces.currentWorkspaceId$.next('foo');
expect(coreStart.savedObjects.client.setCurrentWorkspace).toHaveBeenCalledWith('foo');
});

it('#setup register workspace dropdown menu when setup', async () => {
const setupMock = coreMock.createSetup();
const workspacePlugin = new WorkspacePlugin();
await workspacePlugin.setup(setupMock);
expect(setupMock.chrome.registerCollapsibleNavHeader).toBeCalledTimes(1);
});
});
Loading
Loading