Skip to content

Commit

Permalink
moving the functionality to workspace_route
Browse files Browse the repository at this point in the history
  • Loading branch information
mbondyra committed Sep 7, 2021
1 parent 2203f6b commit 8508c8a
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 35 deletions.
11 changes: 9 additions & 2 deletions x-pack/plugins/graph/public/apps/workspace_route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,20 @@ export const WorkspaceRoute = ({
})
);

const { savedWorkspace, indexPatterns, sharingSavedObjectProps } = useWorkspaceLoader({
const loaded = useWorkspaceLoader({
workspaceRef,
store,
savedObjectsClient,
toastNotifications,
spaces,
coreStart,
});

if (!loaded) {
return null;
}

const { savedWorkspace, indexPatterns, sharingSavedObjectProps } = loaded;

if (!savedWorkspace || !indexPatterns) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,4 @@ describe('workspace_layout', () => {
otherObjectPath: '#/workspace/conflictId',
});
});

it('should redirect if outcome is aliasMatch', () => {
shallow(
<WorkspaceLayoutComponent
{...defaultProps}
sharingSavedObjectProps={{ outcome: 'aliasMatch', aliasTargetId: 'aliasMatchId' }}
/>
);
expect(defaultProps.spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith(
'#/workspace/aliasMatchId',
'Graph'
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -180,19 +180,6 @@ export const WorkspaceLayoutComponent = ({
return null;
}, [savedWorkspace.id, sharingSavedObjectProps, spaces, coreStart.http]);

if (spaces && sharingSavedObjectProps?.outcome === 'aliasMatch') {
// We found this object by a legacy URL alias from its old ID; redirect the user to the page with its new ID, preserving any URL hash
const newObjectId = sharingSavedObjectProps?.aliasTargetId!; // This is always defined if outcome === 'aliasMatch'
const newPath = getEditUrl(coreStart.http.basePath.prepend, { id: newObjectId });
spaces.ui.redirectLegacyUrl(
newPath,
i18n.translate('xpack.graph.legacyUrlConflict.objectNoun', {
defaultMessage: 'Graph',
})
);
return null;
}

return (
<Fragment>
<WorkspaceTopNavMenu
Expand Down
75 changes: 75 additions & 0 deletions x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React from 'react';
import { mount } from 'enzyme';
import { useWorkspaceLoader, UseWorkspaceLoaderProps } from './use_workspace_loader';
import { coreMock } from 'src/core/public/mocks';
import { spacesPluginMock } from '../../../spaces/public/mocks';
import { createMockGraphStore } from '../state_management/mocks';
import { Workspace } from '../types';
import { SavedObjectsClientCommon } from 'src/plugins/data/common';
import { act } from 'react-dom/test-utils';

jest.mock('react-router-dom', () => ({
useHistory: () => ({
replace: jest.fn(),
}),
useLocation: () => ({
location: jest.fn(),
}),
useParams: () => ({
id: jest.fn(),
}),
}));

jest.mock('React', () => ({
...jest.requireActual('React'),
useEffect: jest.fn(),
}));

const mockSavedObjectsClient = ({
resolve: jest.fn().mockResolvedValue({
saved_object: { id: 10, _version: '7.15.0', attributes: { wsState: '{}' } },
outcome: 'aliasMatch',
alias_target_id: 'aliasTargetId',
}),
find: jest.fn().mockResolvedValue({ title: 'test' }),
} as unknown) as SavedObjectsClientCommon;

async function setup(props: UseWorkspaceLoaderProps) {
const returnVal = {};
function TestComponent() {
Object.assign(returnVal, useWorkspaceLoader(props));
return null;
}
await act(async () => {
const promise = Promise.resolve();
mount(<TestComponent />);
await act(() => promise);
});
return returnVal;
}

describe('use_workspace_loader', () => {
const defaultProps = {
workspaceRef: { current: {} as Workspace },
store: createMockGraphStore({}).store,
savedObjectsClient: mockSavedObjectsClient,
coreStart: coreMock.createStart(),
spaces: spacesPluginMock.createStartContract(),
};

it('should redirect if outcome is aliasMatch', async () => {
await act(async () => {
await setup((defaultProps as unknown) as UseWorkspaceLoaderProps);
});
expect(defaultProps.spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith(
'#/workspace/aliasTargetId',
'Graph'
);
});
});
32 changes: 25 additions & 7 deletions x-pack/plugins/graph/public/helpers/use_workspace_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,22 @@
* 2.0.
*/

import { SavedObjectsClientContract, ToastsStart } from 'kibana/public';
import { SavedObjectsClientContract } from 'kibana/public';
import { useEffect, useState } from 'react';
import { useHistory, useLocation, useParams } from 'react-router-dom';
import { i18n } from '@kbn/i18n';
import { CoreStart } from 'kibana/public';
import { GraphStore } from '../state_management';
import { GraphWorkspaceSavedObject, IndexPatternSavedObject, Workspace } from '../types';
import { getEmptyWorkspace, getSavedWorkspace } from './saved_workspace_utils';

interface UseWorkspaceLoaderProps {
import { getEditUrl } from '../services/url';
import { SpacesApi } from '../../../spaces/public';
export interface UseWorkspaceLoaderProps {
store: GraphStore;
workspaceRef: React.MutableRefObject<Workspace | undefined>;
savedObjectsClient: SavedObjectsClientContract;
toastNotifications: ToastsStart;
spaces: SpacesApi;
coreStart: CoreStart;
}

interface WorkspaceUrlParams {
Expand All @@ -29,10 +32,11 @@ export interface SharingSavedObjectProps {
}

export const useWorkspaceLoader = ({
coreStart,
spaces,
workspaceRef,
store,
savedObjectsClient,
toastNotifications,
}: UseWorkspaceLoaderProps) => {
const [indexPatterns, setIndexPatterns] = useState<IndexPatternSavedObject[]>();
const [savedWorkspace, setSavedWorkspace] = useState<GraphWorkspaceSavedObject>();
Expand Down Expand Up @@ -82,7 +86,7 @@ export const useWorkspaceLoader = ({
}> {
return id
? await getSavedWorkspace(savedObjectsClient, id).catch(function (e) {
toastNotifications.addError(e, {
coreStart.notifications.toasts.addError(e, {
title: i18n.translate('xpack.graph.missingWorkspaceErrorMessage', {
defaultMessage: "Couldn't load graph with ID",
}),
Expand All @@ -101,6 +105,19 @@ export const useWorkspaceLoader = ({
sharingSavedObjectProps: fetchedSharingSavedObjectProps,
} = await fetchSavedWorkspace();

if (spaces && fetchedSharingSavedObjectProps?.outcome === 'aliasMatch') {
// We found this object by a legacy URL alias from its old ID; redirect the user to the page with its new ID, preserving any URL hash
const newObjectId = fetchedSharingSavedObjectProps?.aliasTargetId!; // This is always defined if outcome === 'aliasMatch'
const newPath = getEditUrl(coreStart.http.basePath.prepend, { id: newObjectId });
spaces.ui.redirectLegacyUrl(
newPath,
i18n.translate('xpack.graph.legacyUrlConflict.objectNoun', {
defaultMessage: 'Graph',
})
);
return null;
}

/**
* Deal with situation of request to open saved workspace. Otherwise clean up store,
* when navigating to a new workspace from existing one.
Expand All @@ -124,8 +141,9 @@ export const useWorkspaceLoader = ({
history,
savedObjectsClient,
setSavedWorkspace,
toastNotifications,
coreStart,
workspaceRef,
spaces,
]);

return { savedWorkspace, indexPatterns, sharingSavedObjectProps };
Expand Down

0 comments on commit 8508c8a

Please sign in to comment.