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

[Workspace] Add workspace column to saved objects page #6225

Merged
merged 12 commits into from
Apr 3, 2024
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- [Workspace] Validate if workspace exists when setup inside a workspace ([#6154](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/6154))
- [Workspace] Register a workspace dropdown menu at the top of left nav bar ([#6150](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/6150))
- [Multiple Datasource] Add icon in datasource table page to show the default datasource ([#6231](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/6231))
- [Workspace] Add workspaces column to saved objects page ([#6225](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/6225))

### 🐛 Bug Fixes

Expand Down

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,50 @@ 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('columns') as any[];
Hailong-am marked this conversation as resolved.
Show resolved Hide resolved
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') as any[];
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 {
// first workspace user have permission
Hailong-am marked this conversation as resolved.
Show resolved Hide resolved
const [workspaceId] = object.workspaces.filter((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 @@
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 @@
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 @@
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,17 @@

componentDidMount() {
this._isMounted = true;

this.subscribleWorkspace();
Hailong-am marked this conversation as resolved.
Show resolved Hide resolved
this.fetchSavedObjects();
this.fetchCounts();
}

componentWillUnmount() {
this._isMounted = false;
this.debouncedFetchObjects.cancel();
Hailong-am marked this conversation as resolved.
Show resolved Hide resolved
this.currentWorkspaceIdSubscription?.unsubscribe();
this.workspacesSubscription?.unsubscribe();

Check warning on line 192 in src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx

View check run for this annotation

Codecov / codecov/patch

src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx#L191-L192

Added lines #L191 - L192 were not covered by tests
}

fetchCounts = async () => {
Expand Down Expand Up @@ -246,6 +257,19 @@
this.setState({ isSearching: true }, this.debouncedFetchObjects);
};

subscribleWorkspace = () => {
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 });
});
};

fetchSavedObject = (type: string, id: string) => {
this.setState({ isSearching: true }, () => this.debouncedFetchObject(type, id));
};
Expand Down Expand Up @@ -802,6 +826,8 @@
filteredItemCount,
isSearching,
savedObjectCounts,
availableWorkspaces,
currentWorkspaceId,
} = this.state;
const { http, allowedTypes, applications, namespaceRegistry } = this.props;

Expand Down Expand Up @@ -889,6 +915,8 @@
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 @@ -6,6 +6,6 @@
"requiredPlugins": [
"savedObjects"
],
"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} />;

Check warning on line 42 in src/plugins/workspace/public/components/workspace_column/workspace_column.tsx

View check run for this annotation

Codecov / codecov/patch

src/plugins/workspace/public/components/workspace_column/workspace_column.tsx#L42

Added line #L42 was not covered by tests
},
},
loadData: () => {
return Promise.resolve(undefined);

Check warning on line 46 in src/plugins/workspace/public/components/workspace_column/workspace_column.tsx

View check run for this annotation

Codecov / codecov/patch

src/plugins/workspace/public/components/workspace_column/workspace_column.tsx#L46

Added line #L46 was not covered by tests
},
};
}
Loading
Loading