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

[Backport 2.x] [Workspace] Add workspace column to saved objects page #6529

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { actionServiceMock } from '../../../services/action_service.mock';
import { columnServiceMock } from '../../../services/column_service.mock';
import { SavedObjectsManagementAction } from '../../..';
import { Table, TableProps } from './table';
import { WorkspaceAttribute } from 'opensearch-dashboards/public';

const defaultProps: TableProps = {
basePath: httpServiceMock.createSetupContract().basePath,
Expand Down Expand Up @@ -115,6 +116,52 @@ describe('Table', () => {
expect(component).toMatchSnapshot();
});

it('should render gotoApp link correctly for workspace', () => {
const item = {
id: 'dashboard-1',
type: 'dashboard',
workspaces: ['ws-1'],
attributes: {},
references: [],
meta: {
title: `My-Dashboard-test`,
icon: 'indexPatternApp',
editUrl: '/management/opensearch-dashboards/objects/savedDashboards/dashboard-1',
inAppUrl: {
path: '/app/dashboards#/view/dashboard-1',
uiCapabilitiesPath: 'dashboard.show',
},
},
};
const props = {
...defaultProps,
availableWorkspaces: [{ id: 'ws-1', name: 'My workspace' } as WorkspaceAttribute],
items: [item],
};
// not in a workspace
let component = shallowWithI18nProvider(<Table {...props} />);

let table = component.find('EuiBasicTable');
let columns = table.prop<
Array<{ render: (id: string, record: unknown) => React.ReactElement }>
>('columns');
let content = columns[1].render('My-Dashboard-test', item);
expect(content.props.href).toEqual('http://localhost/w/ws-1/app/dashboards#/view/dashboard-1');

// in a workspace
const currentWorkspaceId = 'foo-ws';
component = shallowWithI18nProvider(
<Table {...props} currentWorkspaceId={currentWorkspaceId} />
);

table = component.find('EuiBasicTable');
columns = table.prop('columns');
content = columns[1].render('My-Dashboard-test', item);
expect(content.props.href).toEqual(
`http://localhost/w/${currentWorkspaceId}/app/dashboards#/view/dashboard-1`
);
});

it('should handle query parse error', () => {
const onQueryChangeMock = jest.fn();
const customizedProps = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* under the License.
*/

import { IBasePath } from 'src/core/public';
import { IBasePath, WorkspaceAttribute } from 'src/core/public';
import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import {
Expand Down Expand Up @@ -56,6 +56,7 @@ import {
SavedObjectsManagementAction,
SavedObjectsManagementColumnServiceStart,
} from '../../../services';
import { formatUrlWithWorkspaceId } from '../../../../../../core/public/utils';

export interface TableProps {
basePath: IBasePath;
Expand Down Expand Up @@ -83,6 +84,8 @@ export interface TableProps {
onShowRelationships: (object: SavedObjectWithMetadata) => void;
canGoInApp: (obj: SavedObjectWithMetadata) => boolean;
dateFormat: string;
availableWorkspaces?: WorkspaceAttribute[];
currentWorkspaceId?: string;
}

interface TableState {
Expand Down Expand Up @@ -177,8 +180,12 @@ export class Table extends PureComponent<TableProps, TableState> {
columnRegistry,
namespaceRegistry,
dateFormat,
availableWorkspaces,
currentWorkspaceId,
} = this.props;

const visibleWsIds = availableWorkspaces?.map((ws) => ws.id) || [];

const pagination = {
pageIndex,
pageSize,
Expand Down Expand Up @@ -231,9 +238,19 @@ export class Table extends PureComponent<TableProps, TableState> {
if (!canGoInApp) {
return <EuiText size="s">{title || getDefaultTitle(object)}</EuiText>;
}
return (
<EuiLink href={basePath.prepend(path)}>{title || getDefaultTitle(object)}</EuiLink>
);
let inAppUrl = basePath.prepend(path);
if (object.workspaces?.length) {
if (currentWorkspaceId) {
inAppUrl = formatUrlWithWorkspaceId(path, currentWorkspaceId, basePath);
} else {
// find first workspace user have permission
const workspaceId = object.workspaces.find((wsId) => visibleWsIds.includes(wsId));
if (workspaceId) {
inAppUrl = formatUrlWithWorkspaceId(path, workspaceId, basePath);
}
}
}
return <EuiLink href={inAppUrl}>{title || getDefaultTitle(object)}</EuiLink>;
},
} as EuiTableFieldDataColumnType<SavedObjectWithMetadata<any>>,
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
notificationServiceMock,
savedObjectsServiceMock,
applicationServiceMock,
workspacesServiceMock,
} from '../../../../../core/public/mocks';
import { dataPluginMock } from '../../../../data/public/mocks';
import { serviceRegistryMock } from '../../services/service_registry.mock';
Expand Down Expand Up @@ -102,6 +103,7 @@ describe('SavedObjectsTable', () => {
let notifications: ReturnType<typeof notificationServiceMock.createStartContract>;
let savedObjects: ReturnType<typeof savedObjectsServiceMock.createStartContract>;
let search: ReturnType<typeof dataPluginMock.createStartContract>['search'];
let workspaces: ReturnType<typeof workspacesServiceMock.createStartContract>;

const shallowRender = (overrides: Partial<SavedObjectsTableProps> = {}) => {
return (shallowWithI18nProvider(
Expand All @@ -121,6 +123,7 @@ describe('SavedObjectsTable', () => {
notifications = notificationServiceMock.createStartContract();
savedObjects = savedObjectsServiceMock.createStartContract();
search = dataPluginMock.createStartContract().search;
workspaces = workspacesServiceMock.createStartContract();

const applications = applicationServiceMock.createStartContract();
applications.capabilities = {
Expand Down Expand Up @@ -161,6 +164,7 @@ describe('SavedObjectsTable', () => {
goInspectObject: () => {},
canGoInApp: () => true,
search,
workspaces,
};

findObjectsMock.mockImplementation(() => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ import {
OverlayStart,
NotificationsStart,
ApplicationStart,
WorkspacesStart,
WorkspaceAttribute,
} from 'src/core/public';
import { Subscription } from 'rxjs';
import { RedirectAppLinks } from '../../../../opensearch_dashboards_react/public';
import { IndexPatternsContract } from '../../../../data/public';
import {
Expand Down Expand Up @@ -110,6 +113,7 @@ export interface SavedObjectsTableProps {
overlays: OverlayStart;
notifications: NotificationsStart;
applications: ApplicationStart;
workspaces: WorkspacesStart;
perPageConfig: number;
goInspectObject: (obj: SavedObjectWithMetadata) => void;
canGoInApp: (obj: SavedObjectWithMetadata) => boolean;
Expand Down Expand Up @@ -137,10 +141,13 @@ export interface SavedObjectsTableState {
exportAllOptions: ExportAllOption[];
exportAllSelectedOptions: Record<string, boolean>;
isIncludeReferencesDeepChecked: boolean;
currentWorkspaceId?: string;
availableWorkspaces?: WorkspaceAttribute[];
}

export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedObjectsTableState> {
private _isMounted = false;
private currentWorkspaceIdSubscription?: Subscription;
private workspacesSubscription?: Subscription;

constructor(props: SavedObjectsTableProps) {
super(props);
Expand Down Expand Up @@ -172,13 +179,15 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb

componentDidMount() {
this._isMounted = true;
this.subscribeWorkspace();
this.fetchSavedObjects();
this.fetchCounts();
}

componentWillUnmount() {
this._isMounted = false;
this.debouncedFetchObjects.cancel();
this.unSubscribeWorkspace();
}

fetchCounts = async () => {
Expand Down Expand Up @@ -246,6 +255,24 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb
this.setState({ isSearching: true }, this.debouncedFetchObjects);
};

subscribeWorkspace = () => {
const workspace = this.props.workspaces;
this.currentWorkspaceIdSubscription = workspace.currentWorkspaceId$.subscribe((workspaceId) =>
this.setState({
currentWorkspaceId: workspaceId,
})
);

this.workspacesSubscription = workspace.workspaceList$.subscribe((workspaceList) => {
this.setState({ availableWorkspaces: workspaceList });
});
};

unSubscribeWorkspace = () => {
this.currentWorkspaceIdSubscription?.unsubscribe();
this.workspacesSubscription?.unsubscribe();
};

fetchSavedObject = (type: string, id: string) => {
this.setState({ isSearching: true }, () => this.debouncedFetchObject(type, id));
};
Expand Down Expand Up @@ -802,6 +829,8 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb
filteredItemCount,
isSearching,
savedObjectCounts,
availableWorkspaces,
currentWorkspaceId,
} = this.state;
const { http, allowedTypes, applications, namespaceRegistry } = this.props;

Expand Down Expand Up @@ -889,6 +918,8 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb
onShowRelationships={this.onShowRelationships}
canGoInApp={this.props.canGoInApp}
dateFormat={this.props.dateFormat}
availableWorkspaces={availableWorkspaces}
currentWorkspaceId={currentWorkspaceId}
/>
</RedirectAppLinks>
</EuiPageContent>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ const SavedObjectsTablePage = ({
overlays={coreStart.overlays}
notifications={coreStart.notifications}
applications={coreStart.application}
workspaces={coreStart.workspaces}
perPageConfig={itemsPerPage}
goInspectObject={(savedObject) => {
const { editUrl } = savedObject.meta;
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/workspace/opensearch_dashboards.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
"savedObjects",
"opensearchDashboardsReact"
],
"optionalPlugins": [],
"optionalPlugins": ["savedObjectsManagement"],
"requiredBundles": ["opensearchDashboardsReact"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

export { getWorkspaceColumn, WorkspaceColumn } from './workspace_column';
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import { coreMock } from '../../../../../core/public/mocks';
import { render } from '@testing-library/react';
import { WorkspaceColumn } from './workspace_column';

describe('workspace column in saved objects page', () => {
const coreSetup = coreMock.createSetup();
const workspaceList = [
{
id: 'ws-1',
name: 'foo',
},
{
id: 'ws-2',
name: 'bar',
},
];
coreSetup.workspaces.workspaceList$.next(workspaceList);

it('should show workspace name correctly', () => {
const workspaces = ['ws-1', 'ws-2'];
const { container } = render(<WorkspaceColumn coreSetup={coreSetup} workspaces={workspaces} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="euiText euiText--medium"
>
foo | bar
</div>
</div>
`);
});

it('show empty when no workspace', () => {
const { container } = render(<WorkspaceColumn coreSetup={coreSetup} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="euiText euiText--medium"
/>
</div>
`);
});

it('show empty when workspace can not found', () => {
const { container } = render(<WorkspaceColumn coreSetup={coreSetup} workspaces={['ws-404']} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="euiText euiText--medium"
/>
</div>
`);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import React from 'react';
import { EuiText } from '@elastic/eui';
import useObservable from 'react-use/lib/useObservable';
import { i18n } from '@osd/i18n';
import { WorkspaceAttribute, CoreSetup } from '../../../../../core/public';
import { SavedObjectsManagementColumn } from '../../../../saved_objects_management/public';

interface WorkspaceColumnProps {
coreSetup: CoreSetup;
workspaces?: string[];
}

export function WorkspaceColumn({ coreSetup, workspaces }: WorkspaceColumnProps) {
const workspaceList = useObservable(coreSetup.workspaces.workspaceList$);

const wsLookUp = workspaceList?.reduce((map, ws) => {
return map.set(ws.id, ws.name);
}, new Map<string, string>());

const workspaceNames = workspaces?.map((wsId) => wsLookUp?.get(wsId)).join(' | ');

return <EuiText>{workspaceNames}</EuiText>;
}

export function getWorkspaceColumn(
coreSetup: CoreSetup
): SavedObjectsManagementColumn<WorkspaceAttribute | undefined> {
return {
id: 'workspace_column',
euiColumn: {
align: 'left',
field: 'workspaces',
name: i18n.translate('savedObjectsManagement.objectsTable.table.columnWorkspacesName', {
defaultMessage: 'Workspaces',
}),
render: (workspaces: string[]) => {
return <WorkspaceColumn coreSetup={coreSetup} workspaces={workspaces} />;
},
},
loadData: () => {
return Promise.resolve(undefined);
},
};
}
Loading
Loading